-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked_List.cpp
124 lines (114 loc) · 2.62 KB
/
Linked_List.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
112
113
114
115
116
117
118
119
120
121
122
123
124
#include "Linked_List.h"
using namespace std;
Linked_List::Linked_List() : size(0), head(NULL), tail(NULL)
{
}
Linked_List::~Linked_List()
{
while (!is_empty ()) {
remove (0);
}
}
void Linked_List::print(ostream& os)
{
Node* cur = head;
while (cur != NULL) {
os << cur->doc->get_name() << " ";
cur = cur->next;
}
}
bool Linked_List::is_empty()
{
if (size == 0) {
//assert ( head == NULL );
return true;
} else {
return false;
}
}
int Linked_List::get_size()
{
return size;
}
void Linked_List::insert(int index, Document* document)
{
/* you should have a throw mechanism if the index is out of
* range, otherwise, all should work.
*
* use a zero based index, i.e. head = 0.
*/
Node *node = new Node;
node->doc = document;
if (size == 0) {
head = node;
tail = node;
node->doc = doc;
node->next = NULL;
/* you could also try comparing size and index
* if ind >= size, tail; if ind < size, ind middle,
* if ind == 0, ins to head, but make sure about the overlap
* of ins to 0, w/ size == 0, and ins 0 w/ size > 0;
*
* tail should not need to be reset if adding to head
*/
} else if ((size > 0) && (index == 0)) {
node->next = head;
head = node;
} else if ((size > 0) && (index < size)) {
/* find node at index - 1, set pointers
* insert to head has been handled, so this
* case will not handle it
* this also ignores insert to tail, by checking if
* index < size.
*/
Node *preceding = find(index - 1);
node->next = preceding->next;
preceding->next = node;
/* the tail pointer gives quick access to the node
*/
} else if ((size > 0) && (index >= size)) {
tail->next = node;
node->next = NULL;
tail = node;
}
size++;
}
/* find will be a utility function employed by remove
* and insert
*/
Linked_List::Node* Linked_List::find(int index)
{
if ( index < 0 || index > get_size()) {
return null;
} else if (get_size() > 0) {
int count = 0;
Node *target = head;
while (count < size) {
target = target->head;
count++;
}
return target;
}
}
/* use find, dump node pointer
*/
void Linked_List::remove(int index)
{
}
/* find the item using FIND, take its pointer
* then delete it, and deallocate.
*/
bool Linked_List::remove(string name)
{
Node* target = find(string name);
remove (target);
return true;
}
/* public method that returns the actual data item
* contained in the node. Use find, take one step further
* and give the item contained in the node.
*/
Document* Linked_List::retrieve(int index)
{
return find(index);
}