LeetCode 206-Reverse Linked List(反转一个单链表)

xiaoxiao2021-02-28  37

题意:

反转一个单链表。

示例:

输入: 1->2->3->4->5->NULL 输出: 5->4->3->2->1->NULL

进阶: 你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

分析:

头插法。

迭代:

newhead为新链的头, 1、每次从原链head里取出链头,命名为now(待插入元素), 2、更新原链 3、将now,插入到newhead首部

递归: 代码虽短,却很巧妙,见这个链接吧: https://blog.csdn.net/puqutogether/article/details/45487797

代码:

迭代:

class Solution { public ListNode reverseList(ListNode head) { ListNode newhead=null; ListNode now; while(head!=null){ now=head; //取头 head=head.next; //更新原链头 now.next=newhead; //插入新链 newhead=now; //更新新链头 } return newhead; } }

递归:

class Solution { public ListNode reverseList(ListNode head) { if(head==null||head.next==null)return head; ListNode newhead=reverseList(head.next); head.next.next=head; head.next=null; return newhead; } }
转载请注明原文地址: https://www.6miu.com/read-2623305.html

最新回复(0)