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
119 lines (90 loc) · 1.99 KB
/
List.cpp
File metadata and controls
119 lines (90 loc) · 1.99 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
#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)
{
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--;
}
int List::getAt(int j){
Node* tmpPtr=frontPtr;
for (int loc=1; loc!=j; loc++){
tmpPtr = tmpPtr->link;
}
return tmpPtr -> data;
}
void List::display()
{
for(Node*currPtr=frontPtr;currPtr!=nullptr;currPtr=currPtr->link){
cout<<currPtr->data<<"";
}
}
void List:: clear(){
while (num_elements!= 0)
{
remove(1);
}
}
//Implementations of missing operations