-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStringList.cpp
109 lines (90 loc) · 2.07 KB
/
StringList.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
#include "StringList.h"
StringList::StringList():head(nullptr){};
StringList::~StringList(){
Node<string> *cursor = head;
while (cursor != nullptr){
cursor = cursor->getNext();
delete head;
head = cursor;
}
};
Node<string> * StringList::getHead(){
return head;
}
void StringList::insert(string k){
if (contains(k))
return;
//make a new node
Node<string> *newNode = new Node<string>;
newNode->setValue(k);
newNode->setNext(nullptr);
//is the list empty?
if (head == nullptr){
head = newNode;
return;
}
// are we comparing to the first element in the list?
if (head->getValue() > newNode->getValue()){
newNode->setNext(head);
head = newNode;
}
else{ //find the right spot
Node<string> *cursor = head;
while ( (cursor->getNext() != nullptr) && (cursor->getNext()->getValue() < k)){
cursor = cursor->getNext();
}
newNode->setNext(cursor->getNext());
cursor->setNext(newNode);
}
return;
};
void StringList::remove(string k){
if (!contains(k))
return;
Node<string> * cursor;
Node<string> * temp;
//is the list empty?
if (head == nullptr){
return;
}
// are we comparing to the first element in the list?
if (head->getValue() == k){
temp = head;
head = head->getNext();
delete temp;
}
else{ //find the right spot
Node<string> *cursor = head;
while ( (cursor->getNext() != nullptr) && (cursor->getNext()->getValue() < k)){
cursor = cursor->getNext();
}
if (cursor->getNext()->getValue() == k){
temp = cursor->getNext();
cursor->setNext(cursor->getNext()->getNext());
delete temp;
}
}
return;
};
void StringList::display(){
int counter = 0;
Node<string> * cursor = head;
if (head == nullptr) cout << "empty list " << endl;
while (cursor != nullptr){
if (counter > 0) cout << ", ";
cout << cursor->getValue();
cursor = cursor->getNext();
counter++;
if (counter % 10 == 0) cout << endl;
}
cout << endl;
};
bool StringList::contains(string k){
Node<string> * cursor = head;
while (cursor != nullptr){
if (cursor->getValue() == k)
return true;
cursor = cursor->getNext();
}
return false;
};