-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.h
106 lines (86 loc) · 1.7 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
template <typename T>
class Stack
{
public:
Stack();
Stack(const Stack<T>& other);
~Stack();
void Push(const T& data);
void Pop();
T Top();
size_t Size();
private:
struct Node
{
T data;
Node* next;
};
Node* m_Top;
size_t m_Size;
};
/**************************************************************************************/
template <typename T>
Stack<T>::Stack() : m_Top(nullptr), m_Size(0) {}
template <typename T>
Stack<T>::~Stack()
{
while(m_Top)
{
Node* temp = m_Top->next;
delete m_Top;
m_Top = temp;
}
}
template <typename T>
Stack<T>::Stack(const Stack<T>& other)
: m_Top(nullptr), m_Size(0)
{
Node* otherCurrent = other.m_Top;
Node* thisCurrent;
while(otherCurrent)
{
Node* newNode = new Node;
newNode->data = otherCurrent->data;
newNode->next = nullptr;
if(!m_Top)
{
m_Top = newNode;
thisCurrent = newNode;
}
else
{
thisCurrent->next = newNode;
thisCurrent = newNode;
}
otherCurrent = otherCurrent->next;
}
}
template <typename T>
void Stack<T>::Push(const T& data)
{
Node* newNode = new Node;
newNode->data = data;
newNode->next = m_Top;
m_Top = newNode;
++m_Size;
}
template <typename T>
void Stack<T>::Pop()
{
Node* temp = m_Top->next;
delete m_Top;
m_Top = temp;
--m_Size;
}
template <typename T>
T Stack<T>::Top()
{
if(m_Top)
return m_Top->data;
throw std::exception();
}
template <typename T>
size_t Stack<T>::Size()
{
return m_Size;
}