forked from Karlina-Bytes/HashTable_Tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
146 lines (119 loc) · 2.62 KB
/
LinkedList.cpp
File metadata and controls
146 lines (119 loc) · 2.62 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
116
117
118
119
120
121
122
123
124
125
126
127
128
//*****************************************************************
// LinkedList.cpp
// HashTable
//
// Created by Karlina Beringer on June 16, 2014.
//
// This header file contains the Linked List class declaration.
// Hash Table array elements consist of Linked List objects.
//*****************************************************************
#include "LinkedList.h"
// Constructs the empty linked list object.
// Creates the head node and sets length to zero.
LinkedList::LinkedList()
{
head = new Item;
head -> next = NULL;
length = 0;
}
// Inserts an item at the end of the list.
void LinkedList::insertItem( Item * newItem )
{
if (!head -> next)
{
head -> next = newItem;
length++;
return;
}
Item * p = head;
Item * q = head;
while (q)
{
p = q;
q = p -> next;
}
p -> next = newItem;
newItem -> next = NULL;
length++;
}
// Removes an item from the list by item key.
// Returns true if the operation is successful.
bool LinkedList::removeItem( string itemKey )
{
if (!head -> next) return false;
Item * p = head;
Item * q = head;
while (q)
{
if (q -> key == itemKey)
{
p -> next = q -> next;
delete q;
length--;
return true;
}
p = q;
q = p -> next;
}
return false;
}
// Searches for an item by its key.
// Returns a reference to first match.
// Returns a NULL pointer if no match is found.
Item * LinkedList::getItem( string itemKey )
{
Item * p = head;
Item * q = head;
while (q)
{
p = q;
if ((p != head) && (p -> key == itemKey))
return p;
q = p -> next;
}
return NULL;
}
// Displays list contents to the console window.
void LinkedList::printList()
{
if (length == 0)
{
cout << "\n{ }\n";
return;
}
Item * p = head;
Item * q = head;
cout << "\n{ ";
while (q)
{
p = q;
if (p != head)
{
cout << p -> key;
if (p -> next) cout << ", ";
else cout << " ";
}
q = p -> next;
}
cout << "}\n";
}
// Returns the length of the list.
int LinkedList::getLength()
{
return length;
}
// De-allocates list memory when the program terminates.
LinkedList::~LinkedList()
{
Item * p = head;
Item * q = head;
while (q)
{
p = q;
q = p -> next;
if (q) delete p;
}
}
//*****************************************************************
// End of File
//*****************************************************************