1
//數據結構堆棧實現(基于數組)
2
#ifndef STACK_H
3
#define STACK_H
4
template<class T>
5
class Stack
6

{
7
public:
8
Stack(int maxsize=50);
9
virtual ~Stack();
10
bool IsEmpty();
11
Stack<T>& Push(const T &val);
12
Stack<T>& Pop(T &e);
13
T& GetTop() const
{return Data[Top];};
14
int Size() const
{return Top+1;};
15
16
private:
17
T *Data;
18
int MaxSize;
19
int Top;
20
21
};
22
23
24
//-----------------------------------------------------------
25
template<class T>
26
Stack<T>::Stack(int maxsize)
27

{
28
MaxSize=maxsize;
29
Data=new T[MaxSize];
30
Top=-1;
31
}
32
33
//-----------------------------------------------------------
34
template<class T>
35
bool Stack<T>::IsEmpty()
36

{ return Top==-1?true:false;
37
38
}
39
//-----------------------------------------------------------
40
template<class T>
41
Stack<T>::~Stack()
42

{
43
delete[] Data;
44
}
45
//-----------------------------------------------------------
46
template<class T>
47
Stack<T>& Stack<T>::Push(const T &val)
48

{
49
if(Top==MaxSize-1) throw exception("棧上溢");
50
Data[++Top]=val;
51
return *this;
52
}
53
//-----------------------------------------------------------
54
template<class T>
55
Stack<T>& Stack<T>::Pop(T &e)
56

{
57
if(Top==-1) throw exception("棧下溢");
58
e=Data[Top--];
59
return *this;
60
}
61
#endif
//數據結構堆棧實現(基于數組)2
#ifndef STACK_H3
#define STACK_H4
template<class T>5
class Stack6


{7
public:8
Stack(int maxsize=50);9
virtual ~Stack();10
bool IsEmpty();11
Stack<T>& Push(const T &val);12
Stack<T>& Pop(T &e);13

T& GetTop() const
{return Data[Top];};14

int Size() const
{return Top+1;};15

16
private:17
T *Data;18
int MaxSize;19
int Top;20

21
};22

23

24
//-----------------------------------------------------------25
template<class T>26
Stack<T>::Stack(int maxsize)27


{28
MaxSize=maxsize;29
Data=new T[MaxSize];30
Top=-1;31
}32

33
//-----------------------------------------------------------34
template<class T>35
bool Stack<T>::IsEmpty()36


{ return Top==-1?true:false;37

38
}39
//-----------------------------------------------------------40
template<class T>41
Stack<T>::~Stack()42


{43
delete[] Data; 44
}45
//-----------------------------------------------------------46
template<class T>47
Stack<T>& Stack<T>::Push(const T &val)48


{49
if(Top==MaxSize-1) throw exception("棧上溢");50
Data[++Top]=val;51
return *this;52
}53
//-----------------------------------------------------------54
template<class T>55
Stack<T>& Stack<T>::Pop(T &e)56


{57
if(Top==-1) throw exception("棧下溢");58
e=Data[Top--];59
return *this;60
}61
#endif

