Run
#include <iostream>
using namespace std;
struct node {
int num;
struct node * next;
}*head;
void make(int n)//function to build linked list
{
int i, num;
struct node *preptr, *newnode;
if(n >= 1)
{
head = (struct node *)malloc(sizeof(struct node));
cout<<"Enter data of the list:\n"; cin>>num;
head->num = num;
head->next = NULL;
preptr = head;
for(i=2; i<=n; i++) { newnode = (struct node *)malloc(sizeof(struct node)); cin>>num;
newnode->num = num;
newnode->next = NULL;
preptr->next = newnode;
preptr = newnode;
}
preptr->next = head; //linking last node with head node
}
}
void insertEnd(int num1)//function to insert element at end
{
struct node *p;
int a;
a=num1;
struct node *temp=(struct node*)malloc(sizeof(struct node));
temp->num=a;
p=head;
while(p->next!=head)
{
p=p->next;
}
p->next=temp;
temp->next=head;
}
void display()//function to display list
{
struct node *tmp;
int n = 1;
if(head == NULL)
{
cout<<"List is empty";
}
else
{
tmp = head;
cout<<"\nCircular linked list data:\n";
do {
cout<<tmp->num<<" "; tmp = tmp->next;
n++;
}while(tmp != head);
}
}
int main()//main function
{
int n,num1;
head = NULL;
cout<<"Enter the size of circular linked list: "; cin>>n;
make(n);
display();
cout<<"\nEnter data to be inserted at end: "; cin>>num1;
cout<<"\nAfter insertion data at end list is:";
insertEnd(num1);
display();
return 0;
}
Output:
Enter the size of circular linked list: 5
Enter data of the list:
11
21
31
41
51
Circular linked list data:
11 21 31 41 51
Enter data to be inserted at end: 61
After insertion data at end list is:
Circular linked list data:
11 21 31 41 51 61
Login/Signup to comment