Skip to content

Commit 68337b8

Browse files
✨ 💡 Solve LeetCode problem 24. Swap Nodes in Pairs [Medium] [JavaScript] | Runtime: 0 ms (Beats 100%) & Add explanation comments
1 parent 5cc4eef commit 68337b8

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* Problem: 24. Swap Nodes in Pairs
3+
*
4+
* Difficulty: Medium
5+
*
6+
* Language: JavaScript
7+
*
8+
* Performance: Runtime - 0 ms (Beats 100%)
9+
*/
10+
11+
/**
12+
* Swaps every two adjacent nodes in a linked list
13+
*
14+
* @param {ListNode} head - Head of the linked list
15+
*
16+
* @returns {ListNode} - New head of the modified list
17+
*/
18+
const swapPairs = (head) => {
19+
// Return early if list is empty or has only one node
20+
if (!head || !head.next) return head
21+
22+
// Save the second node as the new head after swap
23+
const newHead = head.next
24+
// Recursively swap rest of the list and connect to first node
25+
head.next = swapPairs(newHead.next)
26+
// Connect second node to first node
27+
newHead.next = head
28+
29+
// Return new head after swap
30+
return newHead
31+
}

0 commit comments

Comments
 (0)