-
Notifications
You must be signed in to change notification settings - Fork 1
/
linkedlist.c
133 lines (119 loc) · 2.47 KB
/
linkedlist.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
#include <stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node* link;
};
struct node* head=NULL;
int countnodes(){
struct node* temp=head;
int count=0;
while(temp!=NULL){
count++;
temp=temp->link;
}
return count;
}
void traverse(){
struct node* temp=head;
printf("\n\n");
while(temp!=NULL){
printf("%d\t",temp->data);
temp=temp->link;
}
printf("No of elements : %d\n",countnodes());
printf("\n\n");
}
void insert(int x,int pos){
struct node* newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=x;
newnode->link=NULL;
if(pos==1){
newnode->link=head;
head=newnode;
}
/*else if (pos==(countnodes()+1)){
struct node* temp=head;
struct node* temp1;
while(temp!=NULL){
temp1=temp;
temp=temp->link;
}
temp1->link=newnode;
}*/
else if((pos<=(countnodes()+1)) && pos>1){
struct node* temp=head;
struct node* temp1;
int loc=1;
while(pos!=loc){
temp1=temp;
temp=temp->link;
loc++;
}
newnode->link=temp1->link;
temp1->link=newnode;
}
else printf("\nIMPOSSIBLE!!\n");
}
void delete(int pos){
if(head==NULL){
printf("No Such List\n");
}
else if(pos==1){
struct node* p=head;
head=head->link;
free(p);
}
else if(pos>1 && pos<(countnodes()+1)){
int loc=1;
struct node* temp=head;
struct node* temp1;
while(pos!=loc){
temp1=temp;
temp=temp->link;
loc++;
}
struct node* p=temp1->link;
temp1->link=temp->link;
free(p);
}
else printf("\nIMPOSSIBLE!!\n");
}
void search(int key){
struct node* temp=head;
while(temp!=NULL){
if(temp->data==key){
printf("Element found\n");
return;
}
temp=temp->link;
}
printf("Element not found\n");
}
void main(){
int op,data,pos,key;
while(1){
printf("1.Insertion\n2.Deletion\n3.Searching\n4.Traversal\nSelect the operation:");
scanf("%d",&op);
if(op==1){
printf("Enter the Data:");
scanf("%d",&data);
printf("Enter the position to be inserted:");
scanf("%d",&pos);
insert(data,pos);
}
else if(op==2){
printf("Enter the position to be deleted:");
scanf("%d",&pos);
delete(pos);
}
else if(op==3){
printf("Enter the Elementto be searched:");
scanf("%d",&key);
search(key);
}
else if(op==4){
traverse();
}
}
}