leetcode-206

206. Reverse Linked List

Description

Reverse a singly linked list.

Example:

1
2
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL

Follow up:

A linked list can be reversed either iteratively or recursively. Could you implement both?

Analyse

反转单链表

尝试用迭代和递归两种方法来做

1
2
        1  ->   2   -> 3 -> 4 -> 5
pre -> cur -> next

Code

迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
ListNode* reverseList(ListNode* head)
{
ListNode* pre = NULL;
ListNode* cur = head;
ListNode* next;

while (cur)
{
next = cur->next;
cur->next = pre;
pre = cur;
cur = next;
}

return pre;
}

递归

找到递归子问题

对每个单链表,每次将最后两个 node 的指向反转

举个例子

1
2
3
4
5
1->2->3->4->5
1->2->3->4<-5
1->2->3<-4<-5
1->2<-3<-4<-5
1<-2<-3<-4<-5
1
2
3
4
5
6
7
8
9
10
11
12
13
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}

// lastNode是未逆序的最后一个节点
ListNode lastNode = reverseList(head.next);
// 此时的head是lastNode前面一个节点
head.next.next = head;
head.next = null;

return lastNode;
}