-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
107 lines (81 loc) · 1.39 KB
/
stack.cpp
File metadata and controls
107 lines (81 loc) · 1.39 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
#include "stdafx.h"
#include "stack.h"
//2019.2.13--自己实现一下栈
template<typename T>
CStack<T>::CStack()
{
top = NULL;
}
template<typename T>
CStack<T>::CStack(T val)
{
top = new CNode;
top->data = val;
top->next = NULL;
}
template<typename T>
CStack<T>::~CStack()
{
CNode *tmp_node = NULL;
while (top != NULL)
{
tmp_node = top->next;
delete top;
//top释放之后重新与剩余的链表空间相关联。
top = tmp_node;
}
}
//init the stack
template<typename T>
void CStack<T>::init()
{
if (empty())
{
top = new CNode();
top->data = -1;
top->next = NULL;
}
}
template<typename T>
T CStack<T>::GetTopData()
{
return top->data;
}
//push data into the stack
template<typename T>
void CStack<T>::Push(T val)
{
CNode *new_node = new CNode;
new_node->data = val;
new_node->next = top;
//top指向新的栈顶
top = new_node;
}
//pop the top of stack,means size - 1
template<typename T>
void CStack<T>::Pop()
{
//所谓弹出栈顶,其实就是删除栈顶的节点
CNode *node = top->next;
delete top;
//栈顶指向下一个节点
top = node;
}
//Get the size of stack
template<typename T>
int CStack<T>::Size()
{
int size = 0;
CNode *tmp_node = top;
while (tmp_node != NULL)
{
size++;
tmp_node = tmp_node->next;
}
}
//if empty
template<typename T>
bool CStack<T>::empty()
{
return top == NULL;
}