顺序栈

构造函数中的数组分配和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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值