C++ Code to Swap Nodes in a Doubly Linked List without Modifying Data
#include <iostream>
class Node {
public:
int data;
Node* prev;
Node* next;
};
void swapNodes(Node headRef, Node x, Node y) {
if (x == y) return;
if (x->next == y) {
if (x->prev) x->prev->next = y;
if (y->next) y->next->prev = x;
x->next = y->next;
y->prev = x->prev;
x->prev = y;
y->next = x;
if (headRef == x) headRef = y;
} else if (y->next == x) {
swapNodes(headRef, y, x);
} else {
Node* xPrev = x->prev;
Node* xNext = x->next;
Node* yPrev = y->prev;
Node* yNext = y->next;
if (xPrev) xPrev->next = y;
if (xNext) xNext->prev = y;
if (yPrev) yPrev->next = x;
if (yNext) yNext->prev = x;
x->prev = yPrev;
x->next = yNext;
y->prev = xPrev;
y->next = xNext;
if (headRef == x) headRef = y;
else if (headRef == y) headRef = x;
}
}
void printList(Node* node) {
while (node) {
std::cout << node->data << " ";
node = node->next;
}
std::cout << std::endl;
}
int main() {
Node* head = new Node();
Node* second = new Node();
Node* third = new Node();
Node* fourth = new Node();
head->data = 1;
head->prev = nullptr;
head->next = second;
second->data = 2;
second->prev = head;
second->next = third;
third->data = 3;
third->prev = second;
third->next = fourth;
fourth->data = 4;
fourth->prev = third;
fourth->next = nullptr;
std::cout << "Original list: ";
printList(head);
swapNodes(&head, second, third);
std::cout << "Swapped list: ";
printList(head);
return 0;
}