-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlist.cpp
More file actions
79 lines (72 loc) · 1.36 KB
/
list.cpp
File metadata and controls
79 lines (72 loc) · 1.36 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
#include <iostream>
#include "node.h"
#include "list.h"
List::List() : head(nullptr), tail(nullptr) {}
List::~List() {
for (Node* np = head; np != nullptr;) {
Node* cnp = np;
np = np->next;
delete cnp;
}
}
void List::append(int v) {
Node* np = new Node(v);
if (head == nullptr) {
head = tail = np;
return;
}
tail->next = np;
tail = tail->next;
}
void List::display() {
std::cout << "The Linked List elements are: { ";
for (Node* np = head; np != nullptr; np = np->next) {
if (np != head) {
std::cout << " -> ";
}
std::cout << np->data;
}
std::cout << " }" << std::endl;
}
void List::insert(int n, int x) {
if (head == nullptr) {
append(x);
return;
}
Node* newNodePointer = new Node(x);
for (Node* np = head; np != nullptr; np = np->next) {
if (np->data == n) {
newNodePointer->next = np->next;
np->next = newNodePointer;
if (np == tail) {
tail = tail->next;
}
return;
}
}
tail->next = newNodePointer;
tail = tail->next;
}
void List::remove(int x) {
if (head == nullptr) {
return;
}
if (head->data == x) {
Node *dp = head;
head = head->next;
if (head == nullptr) {
tail = nullptr;
}
delete dp;
}
for (Node* np = head; np != nullptr; np = np->next) {
if (np->next->data == x) {
Node* dp = np->next;
np->next = np->next->next;
if (np->next == nullptr){
tail = np;
}
delete dp;
}
}
}