File tree 2 files changed +57
-0
lines changed
2 files changed +57
-0
lines changed Original file line number Diff line number Diff line change
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
+ } ;
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments