Skip to content

Commit 8fa364b

Browse files
committed
add 206. 反转链表
1 parent 7a12218 commit 8fa364b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// LeetCode 原题:206. 反转链表
2+
// https://leetcode-cn.com/problems/reverse-linked-list/
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* 递归法
13+
* 时间复杂度 O(n)
14+
* 空间复杂度 O(n) 递归深度
15+
* @param {ListNode} head
16+
* @return {ListNode}
17+
*/
18+
var reverseList = function (head) {
19+
// 递归终止条件
20+
if (head === null || head.next === null) {
21+
return head;
22+
}
23+
const node = reverseList(head.next);
24+
// 反转
25+
head.next.next = head;
26+
head.next = null;
27+
return node;
28+
};
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// LeetCode 原题:206. 反转链表
2+
// https://leetcode-cn.com/problems/reverse-linked-list/
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* function ListNode(val, next) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
*/
11+
/**
12+
* 迭代法
13+
* 时间复杂度 O(n)
14+
* 空间复杂度 O(1)
15+
* @param {ListNode} head
16+
* @return {ListNode}
17+
*/
18+
var reverseList = function (head) {
19+
let prev = null;
20+
let cur = head;
21+
let next;
22+
while (cur) {
23+
next = cur.next;
24+
cur.next = prev;
25+
prev = cur;
26+
cur = next;
27+
}
28+
return prev;
29+
};

0 commit comments

Comments
 (0)