构造函数中的数组分配和top的赋值问题。
栈中最后允许存放的位置为 maxSize-1。
SeqStack.h
#include<iostream>
using namespace std;
static const int defalutSize = 100;
template<class T>
class SeqStack{
protected:
int maxSize;
T *elements;
int top;
public:
SeqStack(int sz = defalutSize);
~SeqStack(){ delete[]elements; };
bool push(T& x);
bool pop(T& x);
bool getTop(T& x);
bool isEmpty(){ return (top == -1 ? true : false); }
bool isFull(){ return (top == maxSize - 1 ? true : false); }
int getSize(){ return top + 1; }
void makeEmpty(){ top = -1; }
void output();
};
template<class T>
SeqStack<T>::SeqStack(int sz){
maxSize = sz;
top = -1;
elements = new T[maxSize];
if (elements == NULL){
cout << "内存分配错误!" << endl;
exit(1);
}
}
template<class T>
bool SeqStack<T>::push(T &x){
if (isFull() == true) return false;
top = top + 1;
elements[top] = x;
return true;
}
template<class T>
bool SeqStack<T>::pop(T &x){
if (isEmpty() == true) return false;
x = elements[top];
top--;
return true;
}
template<class T>
bool SeqStack<T>::getTop(T& x){
if (isEmpty() == true) return false;
x = elements[top];
return true;
}
template<class T>
void SeqStack<T>::output(){
cout << "top: ";
for (int i = top; i >= 0; i--){
cout << elements[i] << " ";
}
cout << endl;
}
Test.cpp
#include"SeqStack.h"
#include<string>
using namespace std;
void main(){
SeqStack<string> intStack;
string str1 = "abcd", str2 = "efghji", str3 = "hello,world";
string str4, str5;
intStack.push(str1);
intStack.push(str2);
intStack.push(str3);
intStack.output();
cout<< intStack.getSize() << endl;
intStack.getTop(str4);
cout << str4 << endl;
intStack.pop(str5);
intStack.output();
}