-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsinglyLinkedList.cpp
More file actions
101 lines (97 loc) · 1.77 KB
/
Copy pathsinglyLinkedList.cpp
File metadata and controls
101 lines (97 loc) · 1.77 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
#include <iostream>
#include <stdlib.h>
using namespace std;
/* The Node class */
class Node
{
public:
int get() { return object; };
void set(int object) { this->object = object; };
Node* getNext() { return nextNode; };
void setNext(Node* nextNode) { this->nextNode = nextNode; };
private:
int object;
Node* nextNode;
};
/* The List class */
class List
{
public:
List();
void add(int addObject);
friend void traverse(List list);
private:
int size;
Node* headNode;
Node* currentNode;
Node* lastCurrentNode;
// methods
int get();
bool next();
};
/* Constructor */
List::List()
{
headNode = new Node();
headNode->setNext(NULL);
currentNode = NULL;
lastCurrentNode = NULL;
size = 0;
}
/* add() class method */
void List::add(int addObject)
{
Node* newNode = new Node();
newNode->set(addObject);
if (currentNode != NULL)
{
newNode->setNext(currentNode->getNext());
currentNode->setNext(newNode);
lastCurrentNode = currentNode;
currentNode = newNode;
}
else
{
newNode->setNext(NULL);
headNode->setNext(newNode);
lastCurrentNode = headNode;
currentNode = newNode;
}
size++;
}
/* get() class method */
int List::get()
{
if (currentNode != NULL)
return currentNode->get();
}
/* next() class method */
bool List::next()
{
if (currentNode == NULL) return false;
lastCurrentNode = currentNode;
currentNode = currentNode->getNext();
if (currentNode == NULL || size == 0)
return false;
else
return true;
}
/* Friend function to traverse linked list */
void traverse(List list)
{
Node* savedCurrentNode = list.currentNode;
list.currentNode = list.headNode;
for (int i = 1; list.next(); i++)
{
cout << "Element " << i << " " << list.get() << endl;
}
list.currentNode = savedCurrentNode;
}
int main()
{
List l;
l.add(5);
l.add(6);
l.add(3);
traverse(l);
}