-
Notifications
You must be signed in to change notification settings - Fork 72
/
Copy pathSingly_linked_list_implementation.c
159 lines (147 loc) · 2.82 KB
/
Singly_linked_list_implementation.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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
#include <stdio.h>
#include <malloc.h>
struct node
{
int x;
struct node *nxt;
}*f=NULL,*r=NULL,*p;
void InsertBeg();
void InsertEnd();
void Deletenode();
void Display();
int main()
{
int c,fl=1;
while(fl)
{
printf("1.Insert at the beginning\n2.Insert at the end\n3.Delete a node\n4.Display the list\n5.Exit\nEnter choice:");
scanf("%d",&c);
switch(c)
{
case 1:
{
InsertBeg();
break;
}
case 2:
{
InsertEnd();
break;
}
case 3:
{
Deletenode();
break;
}
case 4:
{
Display();
break;
}
case 5:
{
fl=0;
break;
}
default:
{
printf("Invalid choice.\n");
}
}
}
return 0;
}
void InsertBeg()
{
int a;
printf("Enter data:");
scanf("%d",&a);
p = (struct node*)malloc(sizeof(struct node));
//p= new node;
p->x=a;
p->nxt=NULL;
if(f==NULL)
f=r=p;
else
{
p->nxt=f;
f=p;
}
printf("Inserted successfully.\n");
}
void InsertEnd()
{
int a;
printf("Enter data:");
scanf("%d",&a);
//p=new node;
p=(struct node*)malloc(sizeof(struct node));
p->x=a;
p->nxt=NULL;
if(f==NULL)
f=r=p;
else
{
r->nxt=p;
r=p;
}
printf("Inserted successfully.\n");
}
void Deletenode()
{
int a,fl=0;
//node prep=new node;
struct node *prep= (struct node*)malloc(sizeof(struct node));
printf("%d",f->x);
if(f==NULL)
printf("List empty.\n");
else
{
printf("Enter the data of the node to be deleted:");
scanf("%d",&a);
prep=p=f;
while(p)
{
if(p->x==a)
{
fl=1;
if(p==f)
{
f=p->nxt;
}
else if(p==r)
{
prep->nxt=NULL;
r=prep;
}
else
{
prep->nxt=p->nxt;
}
//delete p;
free(p);
break;
}
else
{
prep=p;
p=p->nxt;
}
}
if(fl)
printf("Deleted successfully.\n");
else
printf("Node not found.\n");
}
}
void Display()
{
printf("The list is: ");
p=f;
while(p)
{
printf("%d ",p->x);
p=p->nxt;
}
printf("\n");
}