-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.hpp
92 lines (76 loc) · 1.71 KB
/
Stack.hpp
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
#ifndef _STACK_HPP_
#define _STACK_HPP_
#include <iostream>
#include <string>
using namespace std;
template<class ElementType>
class Stack {
typedef struct Node{
ElementType data;
Node *next;
} Node;
Node *top;
int num;
public:
Stack<ElementType>();
~Stack();
void push( ElementType );
ElementType pop( void );
ElementType topElement();
void show();
bool empty();
};
template<class ElementType>
Stack<ElementType>::Stack(): num(0) {
top = new Node;
}
template<class ElementType>
Stack<ElementType>::~Stack(){
}
template<class ElementType>
void Stack<ElementType>::push( ElementType str ){
if( num == 0 ){
top->data = str;
}else{
// cout << "push" << str << endl;
Node *oldTop = new Node;
oldTop->data = top->data;
oldTop->next = top->next;
top ->next = oldTop;
top -> data = str;
}
num ++;
}
template<class ElementType>
ElementType Stack<ElementType>::pop( void ){
if( num == 1 ){ num = 0; return top->data; }
if( !num ) cerr << "stack empty" << endl;
ElementType ans = top->data;
Node *t = top;
top = top->next;
delete t;
num --;
// cout << "pop" << ans << endl;
return ans;
}
template<class ElementType>
ElementType Stack<ElementType>::topElement(){
if(empty()) return "null";
return top->data;
}
template<class ElementType>
void Stack<ElementType>::show(){
cout << "stack:";
Node *iterator = top;
for( int i = 0; i < num; ++i ){
cout << iterator->data << " -> ";
iterator = iterator->next;
}
cout << endl;
}
template<class ElementType>
bool Stack<ElementType>::empty(){
if(num) return false;
return true;
}
#endif