[LeetCode] 206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.

Example 1:
Example 1
Input: head = [1,2,3,4,5]
Output: [5,4,3,2,1]

Example 2:
Example 2
Input: head = [1,2]
Output: [2,1]

Example 3:
Input: head = []
Output: []

Constraints:
The number of nodes in the list is the range [0, 5000].
-5000 <= Node.val <= 5000

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

反转链表。
这类reverse的题不会写,会写homebrew也枉然。

思路 - 迭代

首先是 iterative 的思路,创建一个空的指针 pre。当 head 不为空的时候,先存住 head.next,然后 head.next 指向 pre,最后 pre,head,next 三个指针整体往后移动一位。

也分享一个注释写的比较好的discussion一个动图帮助理解。

复杂度

时间O(n)
空间O(1)

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public ListNode reverseList(ListNode head) {
// corner case
if (head == null || head.next == null) {
return head;
}

// normal case
ListNode pre = null;
while (head != null) {
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}

JavaScript实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function(head) {
// corner case
if (head === null || head.next === null) {
return head;
}

// normal case
let pre = null;
while (head !== null) {
let next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
};

思路 - 递归

这道题还有递归的做法。递归的思想是把大的问题拆解成足够小的问题,小的问题解决了,大的问题也就能解决。

复杂度

时间O(n)
空间O(n) - 递归栈空间

代码

Java实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* 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;
}

// 存住next节点
ListNode next = head.next;
// 递归函数处理next以及之后的部分
ListNode newHead = reverseList(next);
// 处理当前节点和next之间的指针
// 本来head的next指针是指向next的,现在要反过来
next.next = head;
head.next = null;
return newHead;
}
}

相关题目

1
2
206. Reverse Linked List
92. Reverse Linked List II

[LeetCode] 206. Reverse Linked List
https://shurui91.github.io/posts/2655630186.html
Author
Aaron Liu
Posted on
October 14, 2019
Licensed under