-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
48 lines (39 loc) · 812 Bytes
/
solution.ts
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
/*
* @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;
* }
*/
interface ListNode {
val: number;
next: ListNode | null;
}
/**
* @param {ListNode} head
* @return {ListNode}
*/
const swapPairs = (head: ListNode | null): ListNode | null => {
// * ['52 ms', '80.94 %', '33.7 MB', '89.47 %']
if (head === null) return null;
const dummy = { next: head } as ListNode;
let cur = dummy;
while (cur.next && cur.next.next) {
const n1 = cur.next!;
const n2 = n1.next!;
const n3 = n2.next;
n1.next = n3;
n2.next = n1;
cur.next = n2;
cur = n1;
}
return dummy.next;
};
// @lc code=end
export { swapPairs };