跳至主要內容

页面配置

张威小于 1 分钟使用指南页面配置使用指南

顺序栈的实现

#include <iostream>
#include <stdexcept>
#include <cstring>
using std::cout;
using std::endl;

class SeqStack {
public:
    SeqStack(int cap = 3)
        :_top(0)
        ,_cap(cap)
    {
        _pstack = new int[_cap]();
    }
    ~SeqStack() {
        delete[] _pstack;//不要用delete
        _pstack = nullptr;
    }

    void push(int val) {
        if(_top == _cap) { //栈满了
            expand(2*_cap);
        }

        _pstack[_top] = val;
        ++_top;
    }

    void pop() {
        if(_top == 0){
            throw "Stack is empty!!!";
        }

        --_top;
    }

    int top() {
        if(_top == 0) {
            throw "Stack is empty!!!";
        }
        return _pstack[_top-1];
    }
    bool empty() {
        return _top == 0;    
    }
private:
    void expand(int size) {
        int* newStack = new int[size];
        memcpy(newStack, _pstack, _top*sizeof(int));
        delete[] _pstack;   //这里也是delete[]
        _pstack = newStack;
        _cap = size;
    }



public:
    int* _pstack;   //指向数据域
    int _top;  //指向栈顶,也是栈的大小
    int _cap;    //栈的容量
};


int main()
{
    SeqStack s;
    s.push(12);
    s.push(17);
    s.push(100);
    s.push(78);
    //cout << s.top() << endl;
    //s.pop();
    //cout << s.top() << endl;
    //s.pop();
    //cout << s.top() << endl;
    //s.pop();
    //cout << s.top() << endl;
    //s.pop();
    
    while(!s.empty()) {
        cout << s.top() << endl;
        s.pop();
    }
    return 0;
}
$./a.out 
78
100
17
12