LeetCode.
206.反转一个单链表。
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
Related Topics 链表
方法1:迭代
思路分析:
申请两个指针,第一个指针叫 pre,初始指向 null
。第二个指针 cur 指向 head,此处cur防止遍历时修改head的值。然后不断遍历 cur。每次迭代到 cur,用一个中间节点tem保存cur.next
,cur.next
指向pre,然后pre前进一位到之前cur的位置,cur前进一位到tem保存的下一个节点位置,cur 变成 null 即代表遍历结束。此时pre 就是最后一个节点。
借用力扣(LeetCode)的作者:wang_ni_ma的一个图,更容易看懂理解。
具体代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null;
ListNode cur = head;
while(cur !=null){
ListNode tem = cur.next;
cur.next = pre;
pre = cur;
cur = tem;
}
return pre;
}
}
方法2:递归
思路分析:
既然是递归,我们就需要知道他递归终止条件是什么。
对于这个题,终止条件很明显就是head == null || head.next == null
。
而且因为是递归,我们就不用考虑他前面具体怎么处理,经过ListNode cur = reverseList(head.next);
处理后,我们只需要关心head和head.next
节点怎么处理就可以了。我们假设head
节点为a,head.next
为b。
因为b要逆序,也就是重新指向a,即让b.next = a
。
但是这里要切记!此时的b.next
指向a,同时a.next
也因为正序没处理,还指向着b。也就是说,a和b成了一个环。因此,我们要断掉这个环,也就是使a.next=null
。
具体代码:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode cur = reverseList(head.next);
head.next.next = head;
head.next = null;
return cur;
}
}