forked from Sai-02/Data-Structures-using-C
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDeletion_in_Sorted_linked_list.c
108 lines (99 loc) · 1.92 KB
/
Deletion_in_Sorted_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
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *link;
};
struct node *deleteNode(struct node *, int);
int haveValue(struct node *, int);
int main()
{
int n;
scanf("%d", &n);
struct node *head = (struct node *)malloc(sizeof(struct node));
head->link = NULL;
struct node *temp;
for (int i = 0; i < n; i++)
{
int value;
scanf("%d", &value);
if (i == 0)
{
head->info = value;
temp = head;
}
else
{
struct node *new = (struct node *)malloc(sizeof(struct node));
new->info = value;
new->link = NULL;
temp->link = new;
temp = temp->link;
}
}
int k;
scanf("%d", &k);
if (!haveValue(head, k))
{
printf("Value do not exist in linked list");
}
else
{
head = deleteNode(head, k);
struct node *temp = head;
while (temp != NULL)
{
printf("%d ", temp->info);
temp = temp->link;
}
}
return 0;
}
struct node *deleteNode(struct node *head, int k)
{
struct node *temp = head;
if (head == NULL)
{
return NULL;
}
if (k == 1)
{
head = head->link;
free(temp);
return head;
}
struct node *prev = head;
temp = head->link;
while (temp != NULL)
{
if (temp->info == k)
{
prev->link = temp->link;
free(temp);
return head;
}
prev = temp;
temp = temp->link;
}
return head;
}
int haveValue(struct node *head, int k)
{
struct node *temp = head;
int i = 1;
while (temp != NULL)
{
if (temp->info > k)
{
return 0;
}
else if (temp->info == k)
{
return 1;
}
temp = temp->link;
i++;
}
return 0;
}