#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* left;
Node* right;
Node(int val) : data(val), left(nullptr), right(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->left = head;
head->left = head;
} else {
Node* last = head->left;
last->right = newNode;
newNode->left = last;
newNode->right = head;
head->left = newNode;
}
}
// Function to insert a node into a sorted circular doubly linked list
CircularDoublyLinkedList I(CircularDoublyLinkedList SCDL, Node* x) {
// If list is empty, x becomes the head
if (SCDL.head == nullptr) {
x->left = x;
x->right = x;
head = x;
SCDL.head = head;
return SCDL;
}
Node* current = SCDL.head;
// Finding position to insert x
while (true) {
if (current->data >= x->data) {
break;
}
if (current->right == head) {
break;
}
current = current->right;
}
// Inserting x before the current node
if (x->data < current->data) {
x->left = current->left;
x->right = current;
current->left->right = x;
current->left = x;
// Updating head if x is smallest
if (x->data < head->data) {
head = x;
SCDL.head = head;
}
} else { // Inserting after the current node
x->left = current;
x->right = current->right;
current->right->left = x;
current->right = x;
}
return SCDL;
}
// Utility function to print circular doubly linked list
void printList() {
if (head == nullptr) {
std::cout << "List is empty" << std::endl;
return;
}
Node* temp = head;
do {
std::cout << temp->data << " ";
temp = temp->right;
} while (temp != head);
std::cout << std::endl;
}
};
int main() {
CircularDoublyLinkedList SCDL;
Node* node1 = new Node(10);
Node* node2 = new Node(20);
Node* node3 = new Node(30);
SCDL.insert(node1);
SCDL.insert(node2);
SCDL.insert(node3);
cout<<"Original SCDL: ";
SCDL.printList();
Node* node4 = new Node(15);
Node* node5 = new Node(5);
SCDL.I(SCDL,node4);
SCDL.I(SCDL,node5);
cout<<"Inserting 15 and 5.."<<endl;
cout<<"SCDL after insertion: ";
SCDL.printList();
// Freeing dynamically allocated memory
delete node1;
delete node2;
delete node3;
delete node4;
delete node5;
return 0;
}