数据结构之栈

2017-04-05  本文已影响21人  dongwenbo

栈:操作受限的线性表,后进先出
栈的内部存储既可以用顺序表,也可以用链表,分别称作顺序栈和链栈。

先来实现一个简单的顺序栈
C++

class MyStack {
    char *buffer;
    int size;
    int top;
public:
    MyStack(int size);
    ~MyStack();
    bool stackEmpty();
    bool stackFull();
    void clearStack();
    int stackLength();
    void push(char elem);
    void pop(char &elem);
    void stackTraverse();
};

MyStack::MyStack(int size){
    buffer = new char[size];
    this->size = size;
    top = 0;
}

MyStack::~MyStack(){
    delete [] buffer;
}

bool MyStack::stackEmpty(){
    return top == 0;
}

bool MyStack::stackFull(){
    return top == size;
}

void MyStack::clearStack(){
    top = 0;
}

int MyStack::stackLength(){
    return top; 
}

void MyStack::push(char elem){
    buffer[top++] = elem;
}

void MyStack::pop(char &elem){
    elem = buffer[--top];
}

void MyStack::stackTraverse(){
    for (int i=0; i<top; i++) {
        std::cout<<buffer[i]<<std::endl;
    }
}

上一篇下一篇

猜你喜欢

热点阅读