#include <iostream>
using namespace std;
// Node structure for the circular doubly linked list
struct Node {
int data;
Node* next;
Node* prev;
Node(int val) : data(val), next(nullptr), prev(nullptr) {}
};
class CircularDoublyLinkedList {
private:
Node* head;
public:
CircularDoublyLinkedList() : head(nullptr) {}
// Function to insert a node at the end of the list
void insert(Node* newNode) {
if (head == nullptr) {
head = newNode;
head->next = head;
head->prev = head;
} else {
Node* last = head->prev;
last->next = newNode;
newNode->prev = last;
newNode->next = head;
head->prev = newNode;
}
}
// Function to unlink a node from the list
void unlink(Node* node) {
if (head == nullptr) return;
// If only one node exists, we delete it and set head to nullptr
if (head == node && head->next == head) {
delete head;
head = nullptr;
} else {
// Removing the node from the list
node->prev->next = node->next;
node->next->prev = node->prev;
// updating head node if deleted node is head node
if (head == node) head = node->next;
delete node;
}
}
// Function to splice another circular doubly linked list after a given node
void splice(Node* node, CircularDoublyLinkedList& otherList) {
if (head == nullptr || node == nullptr || otherList.head == nullptr) return;
Node* nextNode = node->next;
Node* otherHead = otherList.head;
Node* otherLast = otherHead->prev;
// Adjusting pointers to splice the lists
node->next = otherHead;
otherHead->prev = node;
nextNode->prev = otherLast;
otherLast->next = nextNode;
otherList.head = nullptr; // The other list becomes empty after splicing
}
// Function to display the circular doubly linked list
void display() {
if (head == nullptr) return;
Node* current = head;
do {
cout << current->data << " ";
current = current->next;
} while (current != head);
cout << endl;
}
};
int main() {
CircularDoublyLinkedList CDL;
Node* node1 = new Node(10);
Node* node2 = new Node(20);
Node* node3 = new Node(30);
Node* node4 = new Node(40);
CDL.insert(node1);
CDL.insert(node2);
CDL.insert(node3);
CDL.insert(node4);
CircularDoublyLinkedList CDL2;
Node* node5 = new Node(50);
Node* node6 = new Node(60);
CDL2.insert(node5);
CDL2.insert(node6);
cout << "Original CDL: ";
CDL.display();
cout << "CDL2: ";
CDL2.display();
// Unlinking the second node
CDL.unlink(node2);
cout << "After unlinking c2: ";
CDL.display();
// Splicing CDL2 after the second node of modified CDL
CDL.splice(node3, CDL2);
cout << "After splicing: ";
CDL.display();
return 0;
}