In: Computer Science
Please find the answer below, all the details are mentioned in the comments.
circular.cpp
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
//structure of the node
struct node {
int data;//to store data
node *next;//to store next
};
//function to delete node form list from the begin
void deleteNode(struct node *&head){
//if list is empty
if(head==NULL){
cout<<"No elements to delete.\n";
}
//if head is the only element in the list
else if(head->next==head){
cout<<head->data<<" deleted.\n";
delete head;//delete head
head = NULL; //set head to NULL
}
//if there is more then one node in the list
else{
//store the head in temp
node *temp;
temp = head;
//last node of the list
node *last;
last = head;
while(last->next!=head)
last = last->next;
//update last to point to head next
last->next = head->next;
cout<<head->data<<" deleted.\n";
//head would be head->next node
head = last->next;
//delete temp node
delete temp;
}
}
//insertNode at the end.
void insertNode (int data, struct node *&head){
node *newNode;
newNode= new node;//creates new node.
newNode->data=data;//stores value.
//If the list is empty, create a single node
if(head==NULL){
newNode->next = newNode;
head = newNode;
}
//if head is the only element in the list
else if(head == head->next){
newNode->next = head->next;
head->next = newNode;
}
// If list is not empty
else{
node *temp;
//last node of the list
temp = head;
while(temp->next!=head)
temp = temp->next;
//next of new node is head
newNode->next = temp->next;
//next of last node is newNode
temp->next = newNode;
}
}
//display th list in doubly link manner
void display(struct node* head) {
node *temp;
temp = head;
printf("\nThe List is:\n");
if(head == NULL){
cout<<"Empty"<<endl;
return;
}
//traverse the list from begin
while (temp->next != head)
{
cout<<temp->data<<"-->";
temp = temp->next;
}
cout<<temp->data<<endl;
}
int main()
{
//head of the list
struct node *head=NULL;
insertNode(1,head);//insert node into the list
insertNode(2,head);//insert node into the list
insertNode(3,head);//insert node into the list
insertNode(4,head);//insert node into the list
insertNode(5,head);//insert node into the list
display(head);
deleteNode(head);
deleteNode(head);
deleteNode(head);
display(head);
deleteNode(head);
deleteNode(head);
display(head);
return 0;
}
Output:
Please let us know in the comments if you face any problems.