Swap Nodesin Pairs Algorithm
The Swap Nodes in Pairs Algorithm is an approach used in computer programming to rearrange or swap adjacent nodes in a linked list with each other, effectively reordering the list in pairs. This algorithm is particularly useful when dealing with data structures that require frequent insertion, deletion, or modification of elements. The primary goal of this algorithm is to ensure that an element in position 'i' is swapped with the element in position 'i+1', where 'i' is an even number, and the process is repeated for every pair of nodes in the list.
The algorithm starts by creating a dummy node, which is a placeholder that will be used to simplify the manipulation of the list. The dummy node is initially connected to the head of the list. Then, a loop is run through the list, and for each iteration, the algorithm swaps the current pair of nodes by updating their next pointers. This process is done by first pointing the previous node's next pointer to the second node in the pair, then pointing the first node's next pointer to the second node's next pointer, and finally pointing the second node's next pointer to the first node. The loop continues until all pairs of nodes have been swapped, and the algorithm then returns the dummy node's next pointer as the new head of the modified linked list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *swapPairs(ListNode *head) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (head == NULL) return NULL;
ListNode prevHead(0);
prevHead.next = head;
ListNode *prev = &prevHead;
ListNode *left = head;
ListNode *right = head->next;
while (left && right) {
prev->next = right;
left->next = right->next;
right->next = left;
prev = left;
left = left->next;
if (left) right = left->next;
else right = NULL;
}
return prevHead.next;
}
};