-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlinked_list.cpp
More file actions
126 lines (113 loc) · 2.25 KB
/
Copy pathlinked_list.cpp
File metadata and controls
126 lines (113 loc) · 2.25 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
/**
* @file
* @author The CS2 TA Team
* @version 1.0
* @date 2013-2014
* @copyright This code is in the public domain.
*
* @brief Example of a linked list class and usage.
*
*/
#include <iostream>
/**
* A class defining the shell of a linked list data structure.
*/
class List
{
/**
* Public methods accessible by external code.
*/
public:
List();
~List();
void insert(int item);
void printList();
/**
* Private data, including structure definition and class variables.
*/
private:
struct Node
{
int data;
Node *next;
/**
* Constructor for a node structure.
*/
Node(int data, Node *next)
{
this->data = data;
this->next = next;
}
};
Node *head;
int num_elements;
};
/**
* List constructor.
*/
List::List()
{
head = nullptr;
num_elements = 0;
}
/**
* List destructor.
*/
List::~List()
{
// TODO: Write the destructor so that this code does not leak memory!
delete head;
}
/**
* insert Insert an integer at the end of the list.
* @param item integer to be inserted at the end of the list
*/
void List::insert(int item)
{
// If we have elements...
if (num_elements > 0)
{
// Set up a pointer to get to end of current list
Node *temp = head;
for (int i = 0; i < num_elements - 1; ++i)
{
temp = temp->next;
}
// temp now points to node at end of list
// Construct our new node, it doesn't point to anything yet
Node *new_node = new Node(item, nullptr);
// Make the old tail point to the new tail
temp->next = new_node;
// and update the number of elements in the list
num_elements++;
}
else
{
head = new Node(item, nullptr);
num_elements++;
}
return;
}
/**
* printList Prints the contents of our list out, one integer per line.
*/
void List::printList()
{
Node *temp = head;
while (temp != nullptr)
{
std::cout << temp->data << std::endl;
temp = temp->next;
}
return;
}
int main(int argc, char const *argv[])
{
List lst;
for (int i = 0; i < 10; ++i)
{
lst.insert(i);
}
lst.printList();
return 0;
}