CircularLL.cpp
CircularLL.cpp
struct Node {
int data;
Node* next;
};
class CircularLinkedList {
private:
Node* head;
Node* cursor; // Points to the last node
public:
CircularLinkedList() : head(nullptr), cursor(nullptr) {}
~CircularLinkedList() {
if (!isEmpty()) {
Node* current = head;
Node* next;
cursor->next = nullptr; // Break the loop
while (current != nullptr) {
next = current->next;
delete current;
current = next;
}
}
}
if (isEmpty()) {
head = cursor = newNode;
newNode->next = head;
} else {
newNode->next = head;
head = newNode;
cursor->next = head;
}
}
if (isEmpty()) {
head = cursor = newNode;
newNode->next = head;
} else {
newNode->next = head;
cursor->next = newNode;
cursor = newNode;
}
}
void deleteFirst() {
if (isEmpty()) {
cout << "List is empty." << endl;
return;
}
if (head == cursor) {
delete head;
head = cursor = nullptr;
} else {
Node* temp = head;
head = head->next;
cursor->next = head;
delete temp;
}
}
void deleteLast() {
if (isEmpty()) {
cout << "List is empty." << endl;
return;
}
if (head == cursor) {
delete cursor;
head = cursor = nullptr;
} else {
Node* current = head;
while (current->next != cursor) {
current = current->next;
}
current->next = head;
delete cursor;
cursor = current;
}
}
if (head->data == key) {
deleteFirst();
return;
}
if (curr == head) {
cout << "Value not found." << endl;
return;
}
prev->next = curr->next;
if (curr == cursor) {
cursor = prev;
}
delete curr;
}
bool search(int key) const {
if (isEmpty()) return false;
int count = 0;
Node* current = head;
do {
count++;
current = current->next;
} while (current != head);
return count;
}
int main() {
CircularLinkedList list;
list.insertAtEnd(1);
list.insertAtEnd(2);
list.insertAtBeginning(3);
list.insertAtEnd(4);
list.deleteFirst();
cout << "After deleting first: ";
list.display();
list.deleteLast();
cout << "After deleting last: ";
list.display();
list.insertAtBeginning(10);
list.insertAtEnd(20);
cout << "After more insertions: ";
list.display();
cout << "Search 20: " << (list.search(20) ? "Found" : "Not Found") << endl;
cout << "Search 5: " << (list.search(5) ? "Found" : "Not Found") << endl;
list.deleteNodeWithValue(2);
cout << "After deleting node with value 2: ";
list.display();
return 0;
}