/
LinkedList.cpp
117 lines (97 loc) · 2.64 KB
/
LinkedList.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
#include "LinkedList.h"
LinkedList::LinkedList()
{
head = nullptr;
tail = nullptr;
size = 0;
//ctor
}
LinkedList::~LinkedList()
{
//dtor
}
LinkedList::LinkedList(const LinkedList& other)
{
//copy ctor
}
LinkedList& LinkedList::operator=(const LinkedList& rhs)
{
if (this == &rhs) return *this; // handle self assignment
//assignment operator
return *this;
}
template <typename T>
void LinkedList<T>::initList(const T& component )
{
if(head != nullptr)
{
deleteList();
}
addToFront(component);
head->next = nullptr;
tail = head;
}
template <typename T>
void LinkedList<T>::addToFront(const T& component)
{
ComponentNode* newComponentPtr = new ComponetNode<T>;
newComponentPtr->component = T(component);
newComponentPtr->next = head;
head = newComponentPtr;
size++;
}
template <typename T>
void LinkedList<T>::addToBack(const T& component)
{
ComponentNode *newComponentPtr = new ComponetNode<T>;
newComponentPtr->component = T(component);
newComponentPtr->next = nullptr;
tail->next = newComponentPtr;
tail = newComponentPtr;
size++;
}
template <typename T>
void LinkedList<T>::removeNode(ComponentNode<T>*& target)
{
ComponentNode* currPtr = head;
ComponentNode* prevPtr = nullptr;
if(target == head) // if the course we are dropping is the head
{
head = head->next; // set head pointer to the next pointer
delete target; // delete the course to be dropped
target = nullptr;
size--;
//cout<<"1st Ship Removed"<<endl<<endl;
}
else
{
while(currPtr!=NULL) // exit loop if we reach the end
{
if(target == currPtr) // Once the current pointer is pointing to the ship to be deleted...
{
if(currPtr == tail)
tail = prevPtr;
prevPtr->next = target->next; // previous pointer skips over the target ship, to the next proceeding in the list
delete target; // delete the dead ship
target = nullptr;
//cout<<"Ship Removed"<<endl<<endl;
size--;
break
}
prevPtr = currPtr;
currPtr = currPtr->next;
}
}
}
template <typename T>
void LinkedList<T>::deleteList()
{
ComponentPtr currPtr = head;
while(currPtr != nullptr)
{
//cout<<"Count is: "<<x<<endl;
removeShip(currPtr); currPtr = head;
}
head = nullptr;
tail = nullptr;
}