-
Notifications
You must be signed in to change notification settings - Fork 0
/
Delete-all-occurrences-of-a-key-in-DLL.cpp
124 lines (77 loc) · 1.74 KB
/
Delete-all-occurrences-of-a-key-in-DLL.cpp
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
124
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
struct Node* prev;
};
void deleteNode(struct Node** head_ref, struct Node* del)
{
/* base case */
if (*head_ref == NULL || del == NULL)
return;
if (*head_ref == del)
*head_ref = del->next;
if (del->next != NULL)
del->next->prev = del->prev;
if (del->prev != NULL)
del->prev->next = del->next;
free(del);
}
void deleteAllOccurOfX(struct Node** head_ref, int x)
{
if ((*head_ref) == NULL)
return;
struct Node* current = *head_ref;
struct Node* next;
while (current != NULL) {
if (current->data == x) {
next = current->next;
deleteNode(head_ref, current);
current = next;
}
else
current = current->next;
}
}
void push(struct Node** head_ref, int new_data)
{
struct Node* new_node =
(struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL)
(*head_ref)->prev = new_node;
(*head_ref) = new_node;
}
void printList(struct Node* head)
{
/* if list is empty */
if (head == NULL)
cout << "Doubly Linked list empty";
while (head != NULL) {
cout << head->data << " ";
head = head->next;
}
}
int main()
{
struct Node* head = NULL;
push(&head, 2);
push(&head, 5);
push(&head, 2);
push(&head, 4);
push(&head, 8);
push(&head, 10);
push(&head, 2);
push(&head, 2);
cout << "Original Doubly linked list:n";
printList(head);
int x = 2;
deleteAllOccurOfX(&head, x);
cout << "\nDoubly linked list after deletion of "
<< x << ":n";
printList(head);
return 0;
}