-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
78 lines (77 loc) · 1.36 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
#ifndef STACK_H_
#define STACK_H_
//用单向链表实现
template<class T>
class stackNode{
public:
stackNode():next(nullptr){}
T data;//当前节点存储的数据
stackNode*next;//指向下一个节点的指针
};
template<class T>
class Stack{
private:
int len;
stackNode<T>*node;//临时节点
stackNode<T>*headnode;//头节点
public:
Stack();
int size(){return len;}
void push(T t);
void pop();
T top();
bool empty();
void clear();
};
template<class T>
Stack<T>::Stack()
{
node=nullptr;
headnode=nullptr;
len=0;
}
template<class T>
void Stack<T>::push(T t)
{
node=new stackNode<T>();
node->data=t;
node->next=headnode;
headnode=node;
++len;
}
template<class T>
void Stack<T>::pop()
{
if(!empty())
{
node=headnode;
headnode=headnode->next;//头节点变成它的下一个节点
delete(node);//删除头节点
--len;
}
}
template<class T>
bool Stack<T>::empty()
{
return len==0;
}
template<class T>
T Stack<T>::top()
{
if(!empty())
return headnode->data;
}
template<class T>
void Stack<T>::clear()
{
while(headnode!=nullptr)
{
node=headnode;
headnode=headnode->next;
delete(node);
}
node=nullptr;
headnode=nullptr;
len=0;
}
#endif