forked from rakati/LSD_C_LAB_S2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatastr.c
123 lines (102 loc) · 2.29 KB
/
datastr.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
#include<stdio.h>
#include<stdlib.h>
struct t_list {
int data;
struct t_list* link;
}; *head
int create_node(int n)
{
/*struct t_list *head=malloc(sizeof(sizeof(struct t_list));
head->data=n;
head->link=NULL;*/
{
struct t_list *newNode, *temp;
int data, i;
head = (struct t_list *)malloc(sizeof(struct t_list));
if(head == NULL)
{
printf("Unable to allocate memory.");
}
else
{
printf("Enter the data of node 1: ");
scanf("%d", &data);
head->data = data;
head->link = NULL;
temp = head;
for(i=2; i<=n; i++)
{
newNode = (struct t_list *)malloc(sizeof(struct t_list));
if(newNode == NULL)
{
printf("Unable to allocate memory.");
break;
}
else
{
printf("Enter the data of node %d: ", i);
scanf("%d", &data);
newNode->data = data;
newNode->link = NULL;
temp->link = newNode;
temp = temp->link;
}
}
printf("SINGLY LINKED LIST CREATED SUCCESSFULLY\n");
}
}
int remove_node(int key)
{
struct t_list *prev, *cur;
while (head != NULL && head->data == key)
{
prev = head;
head = head->link;
free(prev);
return;
}
prev = NULL;
cur = head;
while (cur != NULL)
{
if (cur->data == key)
{
if (prev != NULL)
prev->next = cur->link;
free(cur);
return;
}
prev = cur;
cur = cur->link;
}
}
void displayList()
{
struct t_list *temp;
if (head == NULL)
{
printf("List is empty.\n");
return;
}
temp = head;
while (temp != NULL)
{
printf("%d, ", temp->data);
temp = temp->link;
}
printf("\n");
}
int main()
{
int n, key;
printf("Enter number of node to create: ");
scanf("%d", &n);
create_node(n);
printf("\nData in list before deletion\n");
remove_node();
printf("\nEnter element to delete with key: ");
scanf("%d", &key);
remove_node(key);
printf("\nData in list after deletion\n");
displayList();
return 0;