Leetcode 24 - Swap nodes in pairs

Note:

  • Use a dummyHead to bring some convenience.
  • The terminating conditon is no nodes left or the total number of nodes is odd so there is one node left.

Question:

Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list’s nodes (i.e., only nodes themselves may be changed.)

Example:

img

1
2
Input: head = [1,2,3,4]
Output: [2,1,4,3]

Code:

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
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var swapPairs = function(head) {
let dummyHead = new ListNode();
dummyHead.next = head;
let tmp = dummyHead;
while (tmp.next && tmp.next.next) {
let prevNext = tmp.next;
let prevEnd = tmp.next.next.next;
tmp.next = tmp.next.next;
tmp.next.next = prevNext;

tmp = prevNext;
tmp.next = prevEnd;
}
return dummyHead.next;
};