1: //sqstack.cpp2: #ifndef SQSTACK_CPP_CPP3: #define SQSTACK_CPP_CPP4:5: #include "sqstack.h"6: #include <iostream>7:8: template<class T>9: SqStack<T>::SqStack():10: top(-1),maxsize(MAXSIZE)11: {12: stack = new T[maxsize];13: if(stack == NULL)14: {15: cerr<<"Fail!"<<endl;16: exit(1);17: }18: }19:20: template<class T>21: SqStack<T>::SqStack(int size):22: top(-1),maxsize(size)23: {24: stack = new T[maxsize];25: if(stack == NULL)26: {27: cerr<<"Fail!"<<endl;28: exit(1);29: }30: }31:32: template<class T>33: SqStack<T>::SqStack(T data[],int size):34: top(-1),maxsize(size)35: {36: stack = new T[maxsize];37: if(stack == NULL)38: {39: cerr<<"Fail!"<<endl;40: exit(1);41: }42:43: for(int i = 0; i < maxsize; ++i)44: {45: stack[i] = data[i];46: }47: top += maxsize;48: }49:50: template<class T>51: SqStack<T>::~SqStack()52: {53: delete [] stack;54: }55:56: template<class T>57: void SqStack<T>::Push(const T &item) //压栈58: {59: if(Full())60: {61: cerr<<"stack is full."<<endl;62: exit(1);63: }64:65: top++;66: stack[top] = item;67: }68:69: template<class T>70: T SqStack<T>::Pop()//弹栈71: {72: if(Empty())73: {74: cerr<<"stack is empty."<<endl;75: exit(1);76: }77:78: T data = stack[top];79: top--;80: return data;81: }82:83: template<class T>84: T SqStack<T>::GetTop()//返回栈顶元素85: {86: if(Empty())87: {88: cerr<<"stack is empty."<<endl;89: exit(1);90: }91: return stack[top];92: }93:94: template<class T>95: bool SqStack<T>::Empty() const96: {97: return (-1 == top);98: }99:100: template<class T>101: bool SqStack<T>::Full() const102: {103: return (maxsize -1 == top);104: }105:106: template<class T>107: void SqStack<T>::Clear()108: {109: top = -1;110: }111:112:113: #endif
1: //sqstack.h2:3: #ifndef SQSTACK_H_H4: #define SQSTACK_H_H5:6: #include <iostream>7: using namespace std;8:9: #define MAXSIZE 1010:11: template<class T>12: class SqStack13: {14: int top;15: T * stack;16: int maxsize;17: public:18: SqStack();19: SqStack(int size);20: SqStack(T data[],int size);21: ~SqStack();22:23: void Push(const T &item);24: T Pop();25: T GetTop();26:27: bool Empty() const;28: bool Full() const;29:30: void Clear();31:32: };33:34: #endif
1: //test.cpp2:3: #include "sqstack.h"4: #include "sqstack.cpp"5: #include <iostream>6:7: using namespace std;8:9: int main(int argc, char * argv[])10: {11: int data[] = {1,2,3,4,5,6,7,8,9,10};12: SqStack<int> stack(data,10);13:14: while(!stack.Empty())15: {16: cout<<stack.Pop()<<endl;17: }18: return 0;19: }
另一个问题:两栈共享空间
1: template<class T>2: class SqStack3: {4: int top1;5: int top2;6: T * stack;7: int maxsize;8: public:9: ...10: };