-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedlist.cpp
More file actions
138 lines (127 loc) · 2.36 KB
/
linkedlist.cpp
File metadata and controls
138 lines (127 loc) · 2.36 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
129
130
131
132
133
134
135
136
137
138
#include <iostream>
#include "linkedlist.h"
using namespace std;
int LinkedList::getSize() {
int counter = 0;
Node* temp;
temp = head;
// Iterate through the list
while (temp != NULL) {
temp = temp->next;
counter++;
}
return counter;
}
void LinkedList::insertAt(int value, int pos) {
Node* temp;
if (pos == 0) {
// list is currently empty
if (head == NULL) {
// create a new node named head
head = new (struct Node);
head->value = value;
head->next = NULL;
}
// list is not empty
else {
temp = new (struct Node);
Node* ptr;
ptr = head;
head = temp;
// Set members
head->value = value;
head->next = ptr;
}
}
else if (pos > 0 && pos <=getSize()) {
Node* prev, *curr;
curr = head;
for (int i = 0; i < pos; i++) {
prev = curr;
curr = curr->next;
}
temp = new(struct Node);
prev->next = temp;
temp->next = curr;
temp->value = value;
}
else {
cout << "Out of range" << endl;
}
}
void LinkedList::deleteAt(int pos) {
if (head==NULL) {
cout << "Empty list" <<endl;
}
else {
Node* prev, *curr;
curr = head;
if (pos==0) {
head = curr->next;
} else {
if (pos > 0 && pos < getSize()) {
for (int i = 0; i < pos; i++) {
prev = curr;
curr = curr->next;
}
prev->next = curr->next;
}
else {
cout << "Out of range" << endl;
}
}
}
}
int LinkedList::search(int value) {
Node* temp = head;
int index = -1;
int counter = 0;
while (temp->next != NULL) {
if (temp->value == value) {
index = counter;
return index;
} else {
counter++;
temp = temp->next;
}
}
return index;
}
int LinkedList::findAt(int pos) {
Node* temp = head;
if (pos >= getSize()) {
cout << "Out of range" << endl;
return -1;
}
for (int i = 0; i < pos; i++) {
temp = temp->next;
}
return temp->value;
}
void LinkedList::print() {
// Iterate through list and print out each one
Node* temp = head;
cout << "Head->"<<head->value<<"->";
while (temp->next != NULL) {
temp = temp->next;
cout << temp->value << "->";
}
cout << "NULL" << endl;
}
void LinkedList::updateAt(int newValue, int pos) {
Node* temp = head;
int posCounter = 0;
while (temp->next != NULL) {
if (posCounter == pos) {
temp->value = newValue;
return;
}
else {
temp = temp->next;
posCounter++;
}
}
if (pos>posCounter) {
cout << "Index " << pos << " is out of range." << endl;
}
}