-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
45 lines (40 loc) · 951 Bytes
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
const { ListNode, make_list_node } = require('../utils/');
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
if (!head) {
return null;
}
function switch_two_node(left, right) {
if (right) {
left.next = right.next ? (right.next.next?right.next.next:right.next) : null;
right.next = left?left:null;
}
}
const result = head.next;
if (!result) {
return head;
}
let node = head;
while (node) {
const next = node.next ? node.next.next : null;
switch_two_node(node, node.next);
node = next;
}
return result;
};
const test = make_list_node([1]);
let temp_node = swapPairs(test);
while(temp_node) {
console.log(temp_node.val);
temp_node = temp_node.next;
}