-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.h
136 lines (118 loc) · 2.39 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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/*
* Stack.h
*
* Created on: Mar 15, 2015
* Author: Aurelia
*/
#ifndef STACK_H_
#define STACK_H_
//#include "vector .h"
#include <iostream>
using namespace std;
template <typename ValueType>
class Stack {
public:
Stack();
virtual ~Stack();
int size() const;
bool isEmpty() const;
void clear();
void push(ValueType value);
ValueType pop();
ValueType peek() const;
ValueType & top();
string toString();
private:
Vector<ValueType> elements;
};
template <typename ValueType>
Stack<ValueType>::Stack(){
}
template <typename ValueType>
Stack<ValueType>::~Stack(){
}
template <typename ValueType>
int Stack<ValueType>::size() const{
return elements.size();
}
template <typename ValueType>
bool Stack<ValueType>::isEmpty()const{
return size() == 0;
}
template <typename ValueType>
void Stack<ValueType>::push(ValueType){
elements.add(value);
}
template <typename ValueType>
ValueType Stack<ValueType>::pop(){
if(isEmpty()){
cout<<"Stack kosong"<<endl;
}
ValueType top = elements[elements.size()-1];
elements.remove(elements.size()-1);
return top;
}
template <typename ValueType>
ValueType Stack<ValueType>::peek() const{
if(isEmpty()){
cout<<"Stack kosong"<<endl;
}
return elements.get(elements.size()-1);
}
template <typename ValueType>
ValueType & Stack<ValueType>::top(){
if(isEmpty()){
cout<<"Stack kosong"<<endl;
}
return elements[elements.size()-1];
}
template <typename ValueType>
void Stack<ValueType>::clear(){
elements.clear();
}
template <typename ValueType>
string Stack<ValueType>::toString(){
ostringstream os;
os << *this;
return os.str();
}
template <typename ValueType>
ostream & operator<<(ostream& os, const Stack<ValueType>& stack){
os<<"{";
Stack<ValueType> copy = stack;
Stack<ValueType> reversed;
while (!copy.isEmpty()){
reversed.push(copy.pop());
}
int len = stack.size();
for (int i = 0; i < len; i++){
if(i >0) os << ",";
writeGenericValue(os, reversed.pop(), true);
}
return os << "}";
}
template <typename ValueType>
istream & operator>>(istream& is, Stack<ValueType>& stack){
char ch;
is >> ch;
if (ch != '{'){
cout<<"operator >> : Missing";
}
stack.clear();
is >> ch;
if (ch != '}'){
is.unget();
while (true){
ValueType value;
readGenericValue(is, value);
stack.push(value);
is >> ch;
if (ch == '}') break;
if (ch != ','){
cout<<"operator >>: unexpected character";
}
}
}
return is;
}
#endif /* STACK_H_ */