File tree 1 file changed +54
-0
lines changed
1 file changed +54
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=206 lang=javascript
3
+ *
4
+ * [206] 反转链表
5
+ */
6
+
7
+ // @lc code=start
8
+ /**
9
+ * Definition for singly-linked list.
10
+ * function ListNode(val, next) {
11
+ * this.val = (val===undefined ? 0 : val)
12
+ * this.next = (next===undefined ? null : next)
13
+ * }
14
+ */
15
+ /**
16
+ * @param {ListNode } head
17
+ * @return {ListNode }
18
+ */
19
+ var reverseList = function ( head ) {
20
+ // 递归
21
+
22
+ // 1 -> 2 -> 3 -> 4 -> 5
23
+ // =>
24
+ // 5 -> 4 -> 3 -> 2 -> 1
25
+
26
+ const reverseNode = ( curr , prev ) => {
27
+ if ( curr ) {
28
+ let next = curr . next ;
29
+ curr . next = prev ;
30
+ return reverseNode ( next , curr ) ;
31
+ } else {
32
+ return prev ;
33
+ }
34
+ }
35
+
36
+ return reverseNode ( head , null ) ;
37
+
38
+ // 双指针
39
+
40
+ // let next = null; // 保存 curr 的下一个节点
41
+ // let prev = null;
42
+ // let curr = head;
43
+
44
+ // while (curr) {
45
+ // next = curr.next
46
+ // curr.next = prev;
47
+ // prev = curr;
48
+ // curr = next;
49
+ // }
50
+
51
+ // return prev;
52
+ } ;
53
+ // @lc code=end
54
+
You can’t perform that action at this time.
0 commit comments