顺序栈的实现

#include

using namespace std;

struct SqStack {

int* base;

int* top;

int stacksize;

};

int InitStack(SqStack& S) { //构造空栈

S.top = S.base = new int[1];

if (S.base == 0) return 0;

S.stacksize = 1;

return 1;

}

void enlage(SqStack& S) { //栈空间的扩充

int* newbase = new int[S.stacksize * 2];

if (newbase == 0) exit(0);

for (int i = 0; i < S.stacksize; ++i) {

newbase[i] = S.base[i];

}

delete S.base;

S.base = newbase;

S.top = &S.base[S.stacksize];

S.stacksize *= 2;

}

int Push(SqStack& S, int e) { //入栈

if (S.top - S.base == S.stacksize) {

enlage(S);

}

*S.top = e;

S.top++;

return 1;

}

int GetTop(SqStack S) { //得到栈顶元素

return *(S.top - 1);

}

void Pop(SqStack& S) { //出栈

S.top--;

}

bool empty(SqStack S) { //判断是否为空栈

if (S.base == S.top)

return true;

else

return false;

}

void Clear(SqStack& S) { //清空栈

delete S.base;

}

int main() {

SqStack S;

InitStack(S);

Push(S, 1);

Push(S, 2);

Push(S, 3);

Push(S, 4);

Push(S, 5);

Pop(S);

}

你可能感兴趣的:(顺序栈的实现)