0% found this document useful (0 votes)
8 views3 pages

Circular Linked List

The document contains a C++ implementation of a Circular Linked List with methods to insert, delete, and display nodes. It defines a Node class for individual elements and a CircularLinkedList class to manage the list operations. The main function demonstrates the functionality by inserting and deleting values, showcasing the list's behavior after each operation.

Uploaded by

Ayaan Sidddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views3 pages

Circular Linked List

The document contains a C++ implementation of a Circular Linked List with methods to insert, delete, and display nodes. It defines a Node class for individual elements and a CircularLinkedList class to manage the list operations. The main function demonstrates the functionality by inserting and deleting values, showcasing the list's behavior after each operation.

Uploaded by

Ayaan Sidddiqui
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

#include <iostream>

using namespace std;

class Node {
public:
int data;
Node* next;

Node(int val) {
data = val;
next = nullptr;
}
};

class CircularLinkedList {
private:
Node* tail;

public:
CircularLinkedList() {
tail = nullptr;
}

void insert(int val) {


Node* newNode = new Node(val);
if (!tail) {
tail = newNode;
tail->next = tail;
} else {
newNode->next = tail->next;
tail->next = newNode;
tail = newNode;
}
}

void deleteValue(int val) {


if (!tail) return;

Node* curr = tail->next;


Node* prev = tail;

do {
if (curr->data == val) {
if (curr == tail && curr->next == tail) {
delete curr;
tail = nullptr;
} else {
prev->next = curr->next;
if (curr == tail) tail = prev;
delete curr;
}
return;
}
prev = curr;
curr = curr->next;
} while (curr != tail->next);
}

void display() {
if (!tail) {
cout << "List is empty" << endl;
return;
}

Node* curr = tail->next;


do {
cout << curr->data << " ";
curr = curr->next;
} while (curr != tail->next);
cout << endl;
}
};

int main() {
CircularLinkedList cll;

cll.insert(10);
cll.insert(20);
cll.insert(30);
cll.display(); // Output: 10 20 30

cll.deleteValue(20);
cll.display(); // Output: 10 30

cll.deleteValue(10);
cll.display(); // Output: 30

cll.deleteValue(30);
cll.display(); // Output: List is empty

return 0;
}

You might also like