15.1 C++ Circular Linked List
15.1 C++ Circular Linked List
In this article, you will learn what circular linked list is and its types with
implementation.
A circular linked list is a type of linked list in which the first and the last
nodes are also connected to each other to form a circle.
There are basically two types of circular linked list:
Note: We will be using the singly circular linked list to represent the working
of circular linked list.
struct Node {
int data;
struct Node * next;
};
Each struct node has a data item and a pointer to the next struct node.
Now we will create a simple circular linked list with three items to
understand how this works.
/* Initialize nodes */
struct node *last;
struct node *one = NULL;
struct node *two = NULL;
struct node *three = NULL;
/* Allocate memory */
one = malloc(sizeof(struct node));
two = malloc(sizeof(struct node));
three = malloc(sizeof(struct node));
/* Connect nodes */
one->next = two;
two->next = three;
three->next = one;
In the above code, one, two, and three are the nodes with data items 1, 2,
and 3 respectively.
New node
• store the address of the current first node in the newNode (i.e. pointing
the newNode to the current first node)
• point the last node to newNode (i.e making newNode as head)
Insertion at a node
• store the address of the node next to the last node in temp
#include <iostream>
struct Node {
int data;
struct Node* next;
};
return last;
}
return last;
}
return last;
}
p = last->next;
do {
// if the item is found, place newNode after it
if (p->data == item) {
// allocate memory to the new node
newNode = (struct Node*)malloc(sizeof(struct Node));
p = p->next;
} while (p != last->next);
cout << "\nThe given node is not present in the list" << endl;
return last;
}
// delete a node
void deleteNode(Node** last, int key) {
// if linked list is empty
if (*last == NULL) return;
// if last is to be deleted
if ((*last)->data == key) {
// find the node before the last node
while (temp->next != *last) temp = temp->next;
if (last == NULL) {
cout << "The list is empty" << endl;
return;
}
p = last->next;
do {
cout << p->data << " ";
p = p->next;
} while (p != last->next);
}
int main() {
struct Node* last = NULL;
traverse(last);
traverse(last);
return 0;
}