-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.h
90 lines (78 loc) · 1.54 KB
/
stack.h
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
#ifndef STACK_H
#define STACK_H
using namespace std;
template <class T>
class Stack
{
struct Node
{
T value;
Node* next;
};
int length;
Node* tail;
public:
Stack(): length(0), tail(nullptr)
{
}
void push(T item)
{
Node* newNode = new Node;
newNode->value = item;
newNode->next = tail;
tail = newNode;
length++;
}
T top()
{
return tail->value;
}
void pop()
{
if (tail == nullptr)
{
cout << "The Stack is empty.\n";
return;
}
const Node* temp = tail;
tail = tail->next;
delete temp;
length--;
}
int size() const
{
return length;
}
void clear()
{
delete tail;
length = 0;
}
friend ostream& operator<<(ostream& print, const Stack& stack)
{
if (!stack.size())
{
print << "The Stack is empty.\n";
}
else
{
Node* current = stack.tail;
int temp = stack.size() - 1;
print << "List: {";
print << current->value;
current = current->next;
while (temp--)
{
print << ", " << current->value;
current = current->next;
}
print << "}";
}
return print;
}
~Stack()
{
delete tail;
}
};
#endif