-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathdeleteKeys.cpp
67 lines (61 loc) · 1.48 KB
/
deleteKeys.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
#include <iostream>
#include "basicActions.h"
using namespace std;
/*
Function to Delete Keys.
We can have 3 base cases :
1. If the Key is at the Start of the List, Remove Element at Start.
2. If the Key is at the End of the List, Remove Element at End.
3. If the Key is somewhere in the middle :
-> Set Prev Node's (q) "next" to Current Node's (p) "next".
-> Delete Current Node.
-> Set Current Node to Prev's "next".
*/
Node *deleteKeys(Node *head, int x)
{
Node *p = head, *q = nullptr;
while (p != nullptr)
{
// Element Found at Last.
if (p->next == nullptr && p->data == x)
{
deleteLastElement(head);
break;
}
// Element Found at Start.
else if (p == head && p->data == x)
{
head = deleteFirstElement(head);
p = head;
q = nullptr;
continue;
}
// Element Found Somewhere else.
else if (p->data == x)
{
q->next = p->next;
delete p;
p = q->next;
continue;
}
// Not Found.
q = p;
p = p->next;
continue;
}
return head;
}
int main()
{
Node *head = nullptr;
insertAtEnd(head, 4);
insertAtEnd(head, 1);
insertAtEnd(head, 2);
insertAtEnd(head, 3);
insertAtEnd(head, 4);
insertAtEnd(head, 4);
insertAtEnd(head, 5);
insertAtEnd(head, 4);
head = deleteKeys(head, 3);
displayNodes(head);
}