-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask-1.cpp
More file actions
115 lines (89 loc) · 2.35 KB
/
Copy pathtask-1.cpp
File metadata and controls
115 lines (89 loc) · 2.35 KB
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
#include <iostream>
#include <string>
using namespace std;
class Node {
public:
int data;
Node* next;
Node(int val) {
data = val;
next = nullptr;
}
};
class SinglyLinkedList {
private:
Node* head;
public:
SinglyLinkedList() {
head = nullptr;
}
void insertAtHead(int val) {
Node* newNode = new Node(val);
newNode->next = head;
head = newNode;
}
void insertAtTail(int val) {
Node* newNode = new Node(val);
if (head == nullptr) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != nullptr) {
temp = temp->next;
}
temp->next = newNode;
}
void display() {
Node* temp = head;
while (temp!=nullptr)
{
cout << temp->data << " -> ";
temp = temp->next;
}
cout << "NULL\n";
}
bool search(int val) {
Node* temp = head;
while (temp != nullptr)
{
if (temp->data = val) return true;
temp = temp->next;
}
return false;
}
void deleteNode(int val) {
if (head==nullptr) return;
if (head->data == val) {
Node* toDelete = head;
head = head->next;
delete toDelete;
return;
}
Node* temp = head;
while (temp->next != nullptr && temp->next->data != val)
{
temp = temp->next;
}
if (temp->next == nullptr) return;
Node* toDelete = temp->next;
temp->next = temp->next->next;
delete toDelete;
}
};
int main() {
SinglyLinkedList list;
// Insert at tail
list.insertAtTail(10);
list.insertAtTail(20);
list.insertAtTail(30);
// Insert at head
list.insertAtHead(5);
// Delete 20
list.deleteNode(20);
// Display
list.display(); // EXPECT: 5 -> 10 -> 30 -> NULL
// Search for 30
cout << "Search 30: " << (list.search(30) ? "Found" : "Not Found") << endl;
return 0;
}