Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions circular_linked_list.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include<iostream>
using namespace std;

class Node{
public:
int data;
Node* next;
Node(int data){
this ->data= data;
next = NULL;
}
};

class LinkedList {
public:
Node* head;

LinkedList() {
head = NULL;
}

// Function to insert node at the end of the singly linked list
void insert(int value) {
Node* newNode = new Node(value);

if (head == NULL) {
head = newNode;
return;
}

Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}

// Convert singly linked list to circular linked list
void convertToCircular() {
if (head == NULL) return;

Node* temp = head;

// Traverse till the last node
while (temp->next != NULL) {
temp = temp->next;
}

// Make it circular
temp->next = head;
}

// Display function for circular linked list (print limited nodes to avoid infinite loop)
void displayCircular(int limit = 10) {
if (head == NULL) {
cout << "List is empty\n";
return;
}

Node* temp = head;
int count = 0;

while (temp != NULL && count < limit) {
cout << temp->data << " -> ";
temp = temp->next;
count++;
}
cout << "(back to head...)\n";
}
};

int main() {
LinkedList list;

// Insert values
list.insert(10);
list.insert(20);
list.insert(30);
list.insert(40);

cout << "Converting to Circular Linked List...\n";
list.convertToCircular();

// Display circular list (limited to avoid infinite loop)
list.displayCircular(10);

return 0;
}