-
Notifications
You must be signed in to change notification settings - Fork 1
/
doubly_linked_list.c
127 lines (127 loc) · 2.16 KB
/
doubly_linked_list.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
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* next;
struct node* prev;
}node;
node* start=NULL;
void insert(){
int i,m;
node* t=NULL;
t=(node*)malloc(sizeof(node));
node* r=start;
printf("Enter the position where you want to add the element: ");
scanf("%d",&m);
if ((start==NULL)&&(m!=0)){
printf("Invalid");
}
else if ((start==NULL)&&(m==0)){
printf("Enter data: ");
scanf("%d",&(t->data));
start=t;
start->next=NULL;
start->prev=NULL;
}
else{
for (i = 0; i < m; i++){
if (r->next==NULL){
break;
}
r=r->next;
}
if(r->next==NULL){
printf("Enter data: ");
scanf("%d",&(t->data));
r->next=t;
t->prev=r;
}
else{
printf("Enter data: ");
scanf("%d",&(t->data));
t->next=r->next;
((r->next)->prev)=t;
r->next=t;
t->prev=r;
}
}
}
void delete(){
int i,m;
node* r=start;
printf("Enter the position from where you want to delete the element: ");
scanf("%d",&m);
if((start==NULL)&&(m!=0)){
printf("List is empty\n");
}
else if((start!=NULL)&&(m==0)){
start=start->next;
start->prev=NULL;
free(r);
}
else{
for (i = 0; i < m; i++){
if (r->next==NULL)
break;
r=r->next;
}
if (r->next==NULL){
((r->prev)->next)=NULL;
free(r);
}
else{
((r->prev)->next)=r->next;
((r->next)->prev)=r->prev;
free(r);
}
}
}
void forward(){
node* r=start;
while(r->next!=NULL){
printf("%d ",r->data);
r=r->next;
}
printf("%d ",r->data);
}
void backward(){
node* r=start;
while(r->next!=NULL){
r=r->next;
}
while(r->prev!=NULL){
printf("%d ",r->data);
r=r->prev;
}
printf("%d ",r->data);
}
void display(){
int m;
printf("1. forward order of list\n2. Backward order of list\n");
scanf("%d",&m);
switch(m){
case 1: forward();
break;
case 2: backward();
break;
default: printf("invalid\n");
}
}
void main(){
int n;
while(1){
printf("1. Add a number to the list\n2. Delete a number from the list\n3. View list\n4. Exit\n");
scanf("%d",&n);
switch(n){
case 1: insert();
break;
case 2: delete();
break;
case 3: display();
break;
case 4: exit(0);
break;
default : printf("invalid");
}
}
}