-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.c
More file actions
147 lines (147 loc) · 2.05 KB
/
linkedlist.c
File metadata and controls
147 lines (147 loc) · 2.05 KB
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
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node *next;
}node;
node *X;
node* create(){
node *newNode;
newNode = malloc(sizeof(node));
printf("\nEnter data: ");
scanf("%d",&newNode->data);
return newNode;
}
void display(){
struct node *temp;
if(X==NULL){
printf("\nEmpty List\n");
}
else{
temp=X;
printf("\nList: \n");
while(temp !=NULL){
printf("%d->",temp->data);
temp=temp->next;
}
}
}
void insertAtFront(node *t){
if(X==NULL){
X=t;
X->next =NULL;
}
else{
t->next=X;
X=t;
}
}
void insertAtEnd(node *t){
if(X==NULL){
X==t;
X->next=NULL;
}
else{
node *p=X;
while(p->next !=NULL){
p=p->next;
}
p->next=t;
t->next=NULL;
}
}
void insertAtPos(node *t,int pos){
node *p, *newNode;
int i=1;
p=X;
while(i++<pos-1){
p=p->next;
}
t->next =p->next;
p->next =t;
}
void deleteAtFront(){
node *t=X;
X=X->next;
free(t);
}
void deleteAtEnd(){
node *t,*p=X;
while(p->next->next !=NULL){
p=p->next;
}
t=p->next;
p->next =NULL;
free(t);
}
void deleteAtPos(int pos){
node *p,*t;
int i=1;
p=X;
while(i++<pos-1){
p=p->next;
}
if(p==X){
t=X;
X=X->next;
free(t);
}
else if(p->next->next=NULL){
t=p->next;
p->next=NULL;
free(t);
}
else{
t=p->next;
p->next=t->next;
}
}
int main(){
int n,pos;
while(1){
printf("\n1.Display\n2.Insert at the beginning\n3.Insert at the end\n4.Insert at particular position\n5.Delete from the beginning\n6.Delete from the end\n7.Delete from particular position\n8.Exit\n");
printf("Enter your choice: ");
fflush(stdin);
scanf("%d",&n);
node *t;
switch(n){
case 1:
display();
break;
case 2:
t=create();
insertAtFront(t);
display();
break;
case 3:
t=create();
insertAtEnd(t);
display();
break;
case 4:
printf("Enter the position: ");
scanf("%d",&pos);
t= create(t);
insertAtPos(t,pos);
display();
break;
case 5:
deleteAtFront();
display();
break;
case 6:
deleteAtEnd();
display();
break;
case 7:
printf("Enter the position: ");
scanf("%d",&pos);
deleteAtPos(pos);
display();
break;
case 8:
exit(0);
}
}
return 0;
}