File tree 1 file changed +31
-0
lines changed
00024. Swap Nodes in Pairs
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments