-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLinkedList_Advanced.cpp
111 lines (99 loc) · 2.86 KB
/
LinkedList_Advanced.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
#include <iostream>
using namespace std;
// Definition of Node structure
template <typename T>
struct SNode {
T element;
SNode* next;
SNode(T val) {
element = val;
next = nullptr;
}
};
// Definition of singly linked list class
template <typename T>
class list {
private:
SNode<T>* head;
public:
list() {
head = nullptr;
}
// Function to append elements to the list
void append(T value) {
SNode<T>* newNode = new SNode<T>(value);
if (head == nullptr) {
head = newNode;
}
else {
SNode<T>* current = head;
while (current->next != nullptr) {
current = current->next;
}
current->next = newNode;
}
}
// Function to delete the last occurrence of a value
bool deleteLastOccurrence(T value) {
bool found = false;
if (head == nullptr) // Empty List
return found;
else {
SNode<T>* current = head; // For complete list traversal
SNode<T>* pcurrent = nullptr;
SNode<T>* toremove = nullptr; // For tracking of element
SNode<T>* ptoremove = nullptr;
while (current != nullptr) { // Loop to search for the last occurrence of value
if (current->element == value) {
found = true;
toremove = current;
ptoremove = pcurrent;
}
pcurrent = current;
current = current->next;
}
if (found) {
if (toremove == head) { // Boundary check of head node
head = head->next;
delete toremove;
}
else {
ptoremove->next = toremove->next;
delete toremove;
}
}
}
return found;
}
// Function to print the list
void printList() {
SNode<T>* current = head;
while (current != nullptr) {
cout << current->element << " ";
current = current->next;
}
cout << endl;
}
};
int main() {
list<int> myList;
// Append elements to the list
myList.append(1);
myList.append(2);
myList.append(3);
myList.append(2);
myList.append(4);
myList.append(2);
cout << "Original list: ";
myList.printList();
// Delete the last occurrence of 2
int valueToDelete = 2;
if (myList.deleteLastOccurrence(valueToDelete)) {
cout << "After deleting last occurrence of " << valueToDelete << ": ";
myList.printList();
}
else {
cout << "Value " << valueToDelete << " not found in the list." << endl;
}
return 0;
}