Repository navigation
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
73 lines (67 loc) · 1.49 KB
/
Copy pathLinkedList.cpp
File metadata and controls
73 lines (67 loc) · 1.49 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
// LinkedList.cpp -- class for a linked list as a data structure
#ifndef LINKEDLIST_CPP
#define LINKEDLIST_CPP
#include <iostream>
using namespace std;
template <typename T>
struct Node {
T info;
Node<T> *next;
};
template <typename T>
class LinkedList {
Node<T> *start;
public:
int size = 0;
LinkedList() { start = NULL; }
~LinkedList() { makeEmpty(); }
// inserts at the beginning of the linked list
void insertFront (T & element ) {
Node<T> *newNode = new Node<T>;
newNode->info = element;
newNode->next = start;
start = newNode;
++size;
}
// returns true if element is found; returns false if element is not found
int find (T & target) {
bool found = false;
int index = -1;
Node<T> *ptr = start;
while (ptr != NULL && !found) {
if (ptr->info == target) {
found = true;
++index;
}
else{
ptr = ptr->next;
++index;
}
}
return index;
}
T getLast(){ // returns first item in list.
Node<T> *ptr = start;
while (ptr ->next != NULL) {
ptr = ptr->next;
}
return ptr -> info;
}
bool isEmpty() { return start == NULL; }
void makeEmpty() {
while (start != NULL) {
Node<T> *ptr = start;
start = start->next;
delete ptr;
}
}
friend ostream& operator<< (ostream& os, LinkedList<T>& list) {
Node<T> *ptr = list.start;
while (ptr != NULL) {
os << ptr->info << " ";
ptr = ptr->next;
}
return os;
}
};
#endif