CodeTop
第一天
LeetCode 206. 反转链表
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
示例 1:
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
输入:head = [1,2]
输出:[2,1]
示例 3:
输入:head = []
输出:[]
算法1
递归
思路:reverseList(head) 的作用是把所有由head指向的所有节点进行反转,可以把后面n - 1个结点看成一个整体,先进行反转得到tail 链表,再把第一个结点拼在tail链表的尾部,且第一个结点最后指向null
head.next.next = head;他的作用就是进行反转,
head.next = null,此时变成5->4->null
然后再进行回溯
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null)
return head;
ListNode tail = reverseList(head.next);//tail最终是指向最后一个节点,即翻转链表的开头
head.next.next = head;
head.next = null;
return tail;
}
}
迭代(容易理解)
class Solution {
public ListNode reverseList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode a=head;
ListNode b=head.next;
while(b!=null){
ListNode c=b.next;
b.next=a;
a=b;
b=c;
}
head.next=null;
return a;
}
}
2种代码效果相同,只是起点不一样
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
}