-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsinglyll.c
122 lines (104 loc) · 2.13 KB
/
singlyll.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
#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
void print(struct node *head){
struct node *temp = head;
while(temp!=NULL){
printf("%d ", temp->data);
temp = temp->next;
}
}
void length(struct node *head){
struct node *current = head;
int count = 0;
while(current!=NULL){
count++;
current = current->next;
}
printf("%d",count);
}
//Inserting in linked list at the beginning, anywhere in between or end as specified by position
void insert(struct node **head, int x, int pos){
int k=1;
struct node *p,*q,*newnode;
newnode = (struct node *)malloc(sizeof(struct node));
if(!newnode){
printf("Memory error");
return;
}
newnode->data = x;
p = *head;
//Inserting at beginning
if(pos==1){
newnode->next = p;
*head = newnode;
}
else{
//Traverse the list until the position where we want to insert
while((p!=NULL)&&(k<pos)){
k++;
q = p;
p = p->next;
}
q->next = newnode;
newnode->next = p;
}
}
void delete(struct node **head, int pos){
int k=1;
struct node *p, *q;
if(*head==NULL){
printf("Linked list is empty");
return;
}
p = *head;
if(pos==1){
*head = (*head)->next;
free(p);
return;
}
else{
//Traverse the list until the position of node we want to delete
while((p!=NULL)&&(k<pos)){
k++;
q = p;
p = p->next;
}
if(p==NULL)
printf("Position does not exist");
else{
q->next = p->next;
free(p);
}
}
}
int main(){
int ch,x,poi,pod;
struct node *head = NULL;
do{
printf("\nMenu Options:\n1.Insert element\n2.Delete element\n3.Find length of linked list\n4.Print contents of linked list\n5.Exit\nEnter choice: ");
scanf("%d",&ch);
switch(ch){
case 1: printf("Enter element to be inserted: ");
scanf("%d",&x);
printf("Enter it's position: ");
scanf("%d",&poi);
insert(&head,x,poi);
break;
case 2: printf("Enter position of element to be deleted: ");
scanf("%d",&pod);
delete(&head,pod);
break;
case 3: length(head);
break;
case 4: print(head);
break;
case 5: exit(0);
break;
}
}while(ch!=5);
return 0;
}