Cpp Program for Circular Linked List, Basics to algorithms part 5

Cpp Program for Circular Linked List

Basics to algorithm part-5


We have seen Singly linked list and  doubly linked list , now let us look at Circular linked list . 
Circular linked list is a type of linked list where every time last pointer is pointing to the first node creating a circular queue. We Will be discussing the uses of these data structures in other chapters , but for now we can use circular linked list which require Recursive approach. 


Operations on circular linked list are similar to normal linked list. e.g. Searching, creating, deleting a node. We will see how to make, delete and search an element in a c++ program. 


CPP PROGRAM FOR CIRCULAR LINKED LIST:
/*
main.cpp
circularLinkedList
Created by Sarvesh Bhatnagar on 20/02/18.
Copyright © 2018 www.introtoalgo.com. All rights reserved.
*/
#include <iostream>
using namespace std;
struct circularLinkedList{
int id;
struct circularLinkedList *next;
};
struct circularLinkedList *first,*temp,*last,*a;
void makeCircularLinkedList();
void displayCircularLinkedList();
void deleteNode(int n);
void searchCircularLinkedList(int n);
int main() {
first = NULL;
makeCircularLinkedList();
makeCircularLinkedList();
makeCircularLinkedList();
makeCircularLinkedList();
displayCircularLinkedList();
// deleteNode(7);
searchCircularLinkedList(4);
// displayCircularLinkedList();
return 0;
}
void makeCircularLinkedList(){
temp = new circularLinkedList();
cout<<"Enter id"<<endl;
cin>>temp->id;
if (first == NULL) {
first = temp;
temp->next = temp;
last = temp;
}
else{
last->next = temp;
temp->next = first;
last = temp;
}
}
void displayCircularLinkedList(){
temp = first;
cout<<temp->id<<endl;
temp = temp->next;
while (temp != first) {
cout<<temp->id<<endl;
temp = temp->next;
}
}
void deleteNode(int n){
int count = 0;
first = temp;
while (count < n) {
count++;
a = temp;
temp = temp->next;
}
if (temp == first) {
a=first;
first = temp->next;
last->next = first;
}
else{
if (temp == last) {
last = a;
last->next = first;
}
else{
a->next = temp->next;
}
free(temp);
}
free(a);
}
void searchCircularLinkedList(int n){
int c;
temp = first;
do {
c = temp->id;
if (c == n) {
cout<<"ID FOUND"<<endl;
break;
}
temp = temp->next;
} while (temp != first);
}




Written  By, Sarvesh Bhatnagar




Go To:






Popular Posts