-
Notifications
You must be signed in to change notification settings - Fork 209
/
Insertion In Circular Linked List At Any Position.cpp
89 lines (84 loc) · 1.61 KB
/
Insertion In Circular Linked List At Any Position.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
};
struct node *start = NULL;
struct node *last = NULL;
void insert(int data)
{
struct node *ptr=new node;
ptr->data=data;
if(start==NULL)
{
start=ptr;
last=ptr;
start->next=ptr;
}
else
{
last->next=ptr;
last=ptr;
ptr->next=start;
}
}
void display()
{
struct node *temp;
temp=start;
do
{
cout<<temp->data<<" ";
temp=temp->next;
}while(temp!=start);
}
void insert_node(int key,int pos) //Insertion in Circular linked list at any position
{
struct node *temp=new node;
struct node *ptr;
int count=0;
temp->data=key;
ptr=start;
do
{
if(pos==0)
{
while(ptr->next!=start)
{
ptr=ptr->next;
}
ptr->next=temp;
temp->next=start;
start=temp;
break;
}
else if(count==pos-1)
{
temp->next=ptr->next;
ptr->next=temp;
break;
}
count++;
ptr=ptr->next;
}while(ptr!=start);
}
int main()
{
int i,n,a,b,pos;
for(i=0;i<10;i++)
{
insert(i+10);
}
cout<<"Displaying circular linked list : ";
display();
cout<<"\nEnter the element you want to insert : ";
cin>>a;
cout<<"Enter the position you want to insert (taking first node at 0 position) : ";
cin>>pos;
insert_node(a,pos);
cout<<"\nDisplaying circular linked list after insertion : ";
display();
return 0;
}