File tree 1 file changed +43
-0
lines changed
1 file changed +43
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ * @lc app=leetcode.cn id=24 lang=javascript
3
+ *
4
+ * [24] 两两交换链表中的节点
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 swapPairs = function ( head ) {
20
+ if ( ! head || ! head . next ) {
21
+ return head ;
22
+ }
23
+ const dummyNode = new ListNode ( 0 , head ) ;
24
+ let prev = dummyNode ;
25
+ let curr = head ;
26
+
27
+ // 1 -> 2 -> 3 -> 4
28
+ // =>
29
+ // 2 -> 1 -> 4 -> 3
30
+
31
+ while ( curr && curr . next ) {
32
+ const temp = curr . next . next ;
33
+ prev . next = curr . next ;
34
+ curr . next . next = curr ;
35
+ curr . next = temp ;
36
+ prev = curr ;
37
+ curr = temp ;
38
+ }
39
+
40
+ return dummyNode . next ;
41
+ } ;
42
+ // @lc code=end
43
+
You can’t perform that action at this time.
0 commit comments