-
Notifications
You must be signed in to change notification settings - Fork 0
/
LinkedListDeletion.c
121 lines (112 loc) · 2.59 KB
/
LinkedListDeletion.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
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next;
};
void LinkdeListTraversal(struct Node *ptr)
{
// printf("Data in linked list is: \n");
while (ptr != NULL)
{
printf("%d ", ptr->data);
ptr = ptr->next;
}
}
// Case 1:
struct Node *DeleteBeginning(struct Node *head)
{
struct Node *ptr = (struct Node *)malloc(sizeof(struct Node));
ptr = head;
head = head->next;
free(ptr);
return head;
}
// Case 2:
struct Node *DeleteInBetween(struct Node *head, int index)
{
struct Node *p = (struct Node *)malloc(sizeof(struct Node));
struct Node *q = (struct Node *)malloc(sizeof(struct Node));
p = head;
int i = 0;
while (i != index - 1)
{
p = p->next;
i++;
}
q = p->next;
p->next = q->next;
free(q);
return head;
}
// Case 3:
struct Node *DeleteAtEnd(struct Node *head)
{
struct Node *p = head;
struct Node *q = p->next;
while (q->next != NULL)
{
q = q->next;
p = p->next;
}
p->next = NULL;
free(q);
return head;
}
struct Node *DeleteKey(struct Node *head, int key)
{
struct Node *p = head;
struct Node *q = head->next;
while (q->data != key && q->next != NULL)
{
q = q->next;
p = p->next;
}
if (q->data == key)
{
p->next = q->next;
free(q);
}
return head;
}
int main()
{
struct Node *head;
struct Node *second;
struct Node *third;
struct Node *fourth;
struct Node *fifth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));
fifth = (struct Node *)malloc(sizeof(struct Node));
head->data = 20;
head->next = second;
second->data = 30;
second->next = third;
third->data = 40;
third->next = fourth;
fourth->data = 50;
fourth->next = fifth;
fifth->data = 60;
fifth->next = NULL;
printf("Original List: \n");
LinkdeListTraversal(head);
// head = DeleteBeginning(head);
// printf("\n");
// printf("After Deletion from beginning: \n");
// LinkdeListTraversal(head);
// head = DeleteInBetween(head, 2);
// printf("\n");
// printf("After Deletion from given Index: \n");
// LinkdeListTraversal(head);
// head = DeleteAtEnd(head);
// printf("\n");
// printf("After Deletion from End: \n");
// LinkdeListTraversal(head);
printf("\n");
head = DeleteKey(head, 30);
LinkdeListTraversal(head);
}