forked from BitSails/adts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathList.cpp
More file actions
129 lines (90 loc) · 2.17 KB
/
List.cpp
File metadata and controls
129 lines (90 loc) · 2.17 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
#include "List.h"
#include <iostream>
#include <stdexcept>//used to be able to "throw" exceptions
using namespace std;
class List::Node //self-referential Node class
{
public:
int data = 0;
Node* link = nullptr;
//link is a data member which is a pointer
//to an object of the same type (i.e. Node)
};//end Node class definition (can only be seen by the List class)
List::~List()
{
while(num_elements > 0)
remove(1);
}
int List::size()
{
return num_elements;
}
void List::insert(int val, int k)
{
cout << "Val: " << val << " K: " << k << " Num of Elements: " << num_elements << endl;
if (k < 1 or k > num_elements +1) //if the location is invalid
throw out_of_range("List::insertAt(...)");//throw an "out_of_range" exception
Node* newPtr = new Node{val};
if(k == 1)
{
newPtr->link = frontPtr;
frontPtr = newPtr;
}
else
{
Node* tmpPtr = frontPtr;
int loc = 1;
while( loc != k-1) //get pointer to (k-1)th node
{
tmpPtr = tmpPtr->link;
loc++;
}
newPtr->link = tmpPtr->link;
tmpPtr->link = newPtr;
}//end else
num_elements++;
}
void List::remove(int k)
{
if (k < 1 or k > num_elements)//if the location is invalid
throw out_of_range("List::removeAt(...)");//throw an "out_of_range" exception
Node* delPtr;
if(k == 1)
{
delPtr = frontPtr;
frontPtr = frontPtr->link;
}
else
{
Node* tmpPtr = frontPtr;
int loc = 1;
while(loc != k-1)//get pointer to (k-1)th node
{
tmpPtr = tmpPtr->link;
loc++;
}
delPtr = tmpPtr->link;
tmpPtr->link = delPtr->link;
}
delete delPtr;
num_elements--;
}
//Implementations of missing operations
int List::clear(){
while(num_elements != 0){
remove(1);
num_elements--;
}
}
int List::display(){
for(Node* travPtr = frontPtr; travPtr != nullptr; travPtr = travPtr -> link){
cout << travPtr -> data << endl;
}
}
int List::getAt(int k){//get at k-th position
Node* currPtr = frontPtr;
for(int x = 0; x != k; x++){
currPtr = currPtr -> link; //Traverse the list
}
return currPtr -> data; //Return data
}