Skip to content

Commit 2a1bbae

Browse files
committedFeb 27, 2020
Create 24.两两交换链表中的节点.js
1 parent dabc994 commit 2a1bbae

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed
 

‎24.两两交换链表中的节点.js

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* function ListNode(val) {
4+
* this.val = val;
5+
* this.next = null;
6+
* }
7+
*/
8+
/**
9+
* @param {ListNode} head
10+
* @return {ListNode}
11+
*/
12+
var swapPairs = function(head) {
13+
if (!head.next) {
14+
return head;
15+
}
16+
17+
const v = new ListNode();
18+
v.next = head;
19+
let cur = v;
20+
21+
while (cur) {
22+
const a = cur.next;
23+
const b = a && a.next;
24+
25+
if (b) {
26+
a.next = b.next;
27+
b.next = a;
28+
cur.next = b;
29+
cur = a;
30+
} else {
31+
break;
32+
}
33+
}
34+
35+
return v.next;
36+
};

0 commit comments

Comments
 (0)
Please sign in to comment.