24. Swap Nodes in Pairs
Skills:
Linked List
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
Approach - two pointer
Time and space complexity
Solution
1/**
2 * Definition for singly-linked list.
3 * class ListNode {
4 * val: number
5 * next: ListNode | null
6 * constructor(val?: number, next?: ListNode | null) {
7 * this.val = (val===undefined ? 0 : val)
8 * this.next = (next===undefined ? null : next)
9 * }
10 * }
11 */
12
13function swapPairs(head: ListNode | null): ListNode | null {
14 const dummy = new ListNode(0);
15 dummy.next = head;
16 let prev = dummy;
17 while(prev.next && prev.next.next) {
18 const first_node = prev.next;
19 const second_node = prev.next.next;
20
21 first_node.next = second_node.next;
22 second_node.next = first_node;
23 prev.next = second_node;
24
25 prev = first_node
26 }
27
28 return dummy.next
29};