-
Notifications
You must be signed in to change notification settings - Fork 0
/
24.swap-nodes-in-pairs.js
55 lines (50 loc) · 1 KB
/
24.swap-nodes-in-pairs.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
46
47
48
49
50
51
52
53
54
55
/*
* @lc app=leetcode id=24 lang=javascript
*
* [24] Swap Nodes in Pairs
*/
// @lc code=start
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
// function swapPairs(head) {
// let dummyHead = new ListNode(null)
// dummyHead.next = head
// let p = dummyHead
// while (p.next && p.next.next) {
// let node1 = p.next
// let node2 = node1.next
// let next = node2.next
// // swap
// node2.next = node1
// node1.next = next
// p.next = node2
// // move pointer p to next cycle
// p = node1
// }
// let result = dummyHead.next
// dummyHead = null
// return result
// }
function swapPairs(head) {
if (head === null || head.next === null) {
return head
}
let newHead = head.next
head.next = newHead.next
newHead.next = head
head.next = swapPairs(head.next)
return newHead
}
// @lc code=end
module.exports = {
swapPairs
}