-
Notifications
You must be signed in to change notification settings - Fork 1
/
single linked list create, delete, display
120 lines (112 loc) · 2.33 KB
/
single linked list create, delete, display
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
#include <stdio.h>
#include <stdlib.h>
struct node {
int element;
struct node *p;
} *s;
void create(int n);
void delete_Node(int k);
void display();
int main()
{
int n, k;
printf("Enter the number of nodes: ");
scanf("%d", &n);
create(n);
printf("Elements in the list: \n");
display();
printf("\nEnter the node position you want to delete: ");
scanf("%d", &k);
delete_Node(k);
printf("\Elements in the list are: \n");
display();
return 0;
}
void create(int n)
{
struct node *New, *temp;
int element, i;
s = (struct node *)malloc(sizeof(struct node));
if(s == NULL)
{
printf("Cannot allocate memory!");
}
else
{
printf("Enter the element of node 1: ");
scanf("%d", &element);
s->element = element;
s->p = NULL;
temp = s;
for(i=2; i<=n; i++)
{
New = (struct node *)malloc(sizeof(struct node));
if(New == NULL)
{
printf("Cannot allocate memory!");
break;
}
else
{
printf("Enter the element of node %d: ", i);
scanf("%d", &element);
New->element = element;
New->p = NULL;
temp->p = New;
temp = temp->p;
}
}
printf("Singly linked list created!\n");
}
}
void delete_Node(int k)
{
int i;
struct node *toDel, *prevNode;
if(s == NULL)
{
printf("List is already empty.");
}
else
{
toDel = s;
prevNode = s;
for(i=2; i<=k; i++)
{
prevNode = toDel;
toDel = toDel->p;
if(toDel == NULL)
break;
}
if(toDel != NULL)
{
if(toDel == s)
s = s->p;
prevNode->p = toDel->p;
toDel->p = NULL;
free(toDel);
printf("Node deleted!\n");
}
else
{
printf("Invalid position!");
}
}
}
void display()
{
struct node *temp;
if(s == NULL)
{
printf("Empty list!");
}
else
{
temp = s;
while(temp != NULL)
{
printf("The element is %d\n", temp->element);
temp = temp->p;
}
}
}