24. Swap Nodes in Pairs
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]
Constraints:
- The number of nodes in the list is in the range [0, 100].
- 0 <= Node.val <= 100
From: LeetCode
Link: 24. Swap Nodes in Pairs
Solution:
Ideas:
This function uses a “dummy” node to handle edge cases where the head of the list needs to be swapped. It then iterates through the list, swapping pairs of nodes by adjusting their next pointers. It’s designed to handle lists of any size, including the edge cases of empty lists or lists with a single node, as per the constraints mentioned.
Code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* swapPairs(struct ListNode* head) {
// If the list is empty or has only one node, there's nothing to swap.
if (head == NULL || head->next == NULL) {
return head;
}
// Initialize a 'dummy' node, which points to the head of the list.
// This helps in simplifying the swap logic for the head node.
struct ListNode dummy;
dummy.next = head;
// Initialize 'prev' to start with the 'dummy' node.
struct ListNode* prev = &dummy;
// Loop as long as there are at least two nodes to swap.
while (prev->next != NULL && prev->next->next != NULL) {
// Initialize 'first' and 'second' to the two nodes to swap.
struct ListNode* first = prev->next;
struct ListNode* second = first->next;
// Perform the swap by adjusting the 'next' pointers.
first->next = second->next;
second->next = first;
prev->next = second;
// Move 'prev' two nodes ahead for the next pair of swaps.
prev = first;
}
// The 'dummy' node's next points to the new head of the list after swaps.
return dummy.next;
}