-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cc
129 lines (101 loc) · 1.82 KB
/
stack.cc
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
127
128
129
/*Name: Linked list*
*/
#include <iostream>
using namespace std;
template<typename T>
struct Node
{
T data;
struct Node<T>* next;
};
/**
* Stack: LIFO m_head -> Node -> Node -> Node -> NULL
*/
template<typename T>
class Stack
{
public:
Stack ()
: m_head (0)
{
}
virtual ~Stack ()
{
}
/*API*/
struct Node<T>* Push (T &data); // add in the head (m_head)
struct Node<T>* Pop (); // del in the head (m_head)
void Print ();
private:
bool IsEmpty ();
private:
struct Node<T>* m_head;
};
template<typename T>
bool Stack<T>::IsEmpty ()
{
if (m_head != 0)
return false;
else
return true;
}
template<typename T>
void Stack<T>::Print ()
{
if (IsEmpty () == true)
return;
struct Node<T>* cur = m_head;
while (cur != 0)
{
cout << cur->data << " ";
cur = cur->next;
}
cout << endl;
}
template<typename T>
struct Node<T>* Stack<T>::Pop ()
{
if (IsEmpty () == true)
return m_head;
struct Node<T>* cur = m_head;
m_head = m_head->next;
delete cur;
return m_head;
}
template<typename T>
struct Node<T>* Stack<T>::Push (T &data)
{
if (IsEmpty () == true)
{
//first node
struct Node<T>* node = new struct Node<T>;
node->data = data;
node->next = 0;
m_head = node;
}
else
{
//add to the head
struct Node<T>* node = new struct Node<T>;
node->data = data;
node->next = m_head;
m_head = node;
}
return m_head;
}
int main (int argc, char *argv[])
{
typedef int type;
Stack<type> stack;
struct Node<type> *node;
cout << "Push : " << endl;
int data = 8;
node = stack.Push (data);
node = stack.Push (++data);
node = stack.Push (++data);
stack.Print ();
cout << "Pop : " << endl;
node = stack.Pop ();
stack.Print ();
return 0;
}