LeetCode中文 | 英文
206. 反转链表 | 206. reverseList Linked List (Easy)
Given the head
of a singly linked list, reverseList the list, and return the reverseListd list.
链表反转可以通过头插法实现,较为简单,此处仅讨论其递归实现。
/* 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 last = reverseList(head.next);
head.next.next = head;
head.next = null;
return last;
}
}
根据结点定义,易知,这是无头结点的单链表
递归终止条件:无结点或仅剩唯一结点。
下面以反转1→2→3→4→5为例分析。
先从宏观上分析:
reverseList(2):将2——5反转。
此时,链表结构为:
稍后讨论reveseList(2)为什么返回的是这个结构。
1(head)→2←3←4←5(last)
↓
null
此时,2~5已经完成逆序,只需要再把1加入到序列中即可。
此时,head=1, head→next=2.
令head→next→next = head(原来是2→next=null,现在是2→next=head),head→next=null。此时,链表结构为:
1(head)←2←3←4←5(last)
↓
null
此时,链表完成反转,头结点为last。
下面做详细分析:
reverseList(2)→reverseList(3)→reverseList(4)→reverseList(5)
reverseList(5):
∵ head = 5; head→next = null;
∴ return
reverseList(4):
last = reverseList(5) = 5;
此时,链表结构为:
1→2→3→4(currentHead)→5(last)→null
继续执行。reverseList(4)返回时,链表结构为:
1→2→3→4(currentHead)←5(last)
↓
null
reverseList(3)开始执行时,链表结构为:
1→2→3(currentHead)→4←5(last)
↓
null
reverseList(3)返回时,链表结构为:
1→2→3(currentHead)←4←5(last)
↓
null
所以,reverseList(2)返回时,链表结构为:
1→2(currentHead←3←4←5(last)
↓
null
世界线收束,分析完毕。