-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24-swap-nodes-in-pairs.js
More file actions
55 lines (46 loc) · 1.16 KB
/
24-swap-nodes-in-pairs.js
File metadata and controls
55 lines (46 loc) · 1.16 KB
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
/*
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 1:
Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:
Input: head = []
Output: []
Example 3:
Input: head = [1]
Output: [1]
*/
/**
* 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}
*/
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
var swapPairs = function (head) {
const swapPairsFunc = (head) => {
// base case
if (head == null || head.next == null) {
return head;
}
// Nodes to be swapped
let firstNode = head;
let secondNode = head.next;
// Swapping
firstNode.next = swapPairsFunc(secondNode.next);
secondNode.next = firstNode;
// Now the head is the second node
return secondNode;
};
return swapPairsFunc(head);
};
console.log(swapPairs([1, 2, 3, 4]));