-
Notifications
You must be signed in to change notification settings - Fork 34
/
circularLinkedList.c
137 lines (119 loc) · 2.57 KB
/
circularLinkedList.c
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *create(struct node *tail,int n)
{
struct node *newp;
newp=malloc(sizeof(struct node));
tail=newp;
int i,data;
printf("Enter the data of node 1 : ");
scanf("%d",&data);
newp->data=data;
newp->link=newp;
for(i=2;i<=n;i++)
{
printf("Enter the data for node %d : ",i);
scanf("%d",&data);
newp=malloc(sizeof(struct node));
newp->data=data;
newp->link=tail->link;
tail->link=newp;
tail=tail->link;
}
return tail;
}
struct node *addatend(struct node *tail)
{
int data;
printf("Enter the data for node : ");
scanf("%d",&data);
struct node *newp=malloc(sizeof(struct node));
newp->data=data;
newp->link=tail->link;
tail->link=newp;
tail=tail->link;
return tail;
}
struct node *addatbeg(struct node *tail)
{
int data;
printf("Enter the data for node : ");
scanf("%d",&data);
struct node *newp=malloc(sizeof(struct node));
newp->data=data;
newp->link=tail->link;
tail->link=newp;
return tail;
}
struct node *newnode(struct node *tail)
{
tail=malloc(sizeof(struct node));
int data;
printf("Enter data of node : ");
scanf("%d",&data);
tail->data=data;
tail->link=tail;
return tail;
}
struct node *addatpos(struct node *tail)
{
int data,pos;
printf("\nEnter the position to add new node: ");
scanf("%d",&pos);
struct node *newp=malloc(sizeof(struct node));
struct node *ptr;
ptr=tail;
if(pos==0)
return tail;
else if(pos==1&&tail==NULL)
tail=newnode(tail);
else if(pos==1)
tail=addatbeg(tail);
else
{for(int i=1;i<=pos-1;i++)
ptr=ptr->link;
if(ptr==tail)
tail=addatend(tail);
else
{
printf("Enter the data for node : ");
scanf("%d",&data);
newp->data=data;
newp->link=ptr->link;
ptr->link=newp;
}}
return tail;
}
void print(struct node *tail)
{
struct node *ptr;
if(tail==NULL)
printf("List is empty\n");
else
{ptr=tail->link;
do
{
printf("%d ",ptr->data);
ptr=ptr->link;
} while (ptr!=tail->link);
}
}
void main()
{
int n;
printf("How many nodes do you want in the circular linked list : ");
scanf("%d",&n);
struct node *tail=NULL;
if(n!=0)
tail=create(tail,n);
printf("\nList : \n");
print(tail);
tail=addatpos(tail);
printf("\nList : \n");
print(tail);
}