大家如果发现代码有错误,麻烦评论告知一下!!!
代码如下:
#include <iostream>
using namespace std;const int STACK_INIT_SIZE = 100;
const int STACKINCREMENT = 10;typedef int ElemType;typedef struct
{ElemType *base;ElemType *top;int stacksize;
}SqStack;bool initStack(SqStack &s)
{s.base = new ElemType[STACK_INIT_SIZE];if (!s.base) return false;s.top = s.base;s.stacksize = STACK_INIT_SIZE;return true;
}bool destroyStack(SqStack &s)
{delete[] s.base;s.base = s.top = nullptr;s.stacksize = 0;return true;
}bool clearStack(SqStack &s)
{s.top = s.base;return true;
}bool stackEmpty(SqStack s)
{if (s.top == s.base) return true;return false;
}int stackLength(SqStack s)
{return s.top - s.base;
}bool getTop(SqStack s, ElemType &e)
{if (s.top == s.base) return false;e = *(s.top - 1);return true;
}bool push(SqStack &s, ElemType e)
{if (s.top - s.base >= s.stacksize){ElemType *q = new ElemType[STACK_INIT_SIZE + STACKINCREMENT];if (!q) return false;ElemType *p = s.base;int i = 0;while (p != s.top){q[i++] = *p;p++;}delete[] s.base;s.base = q;s.top = s.base + s.stacksize;s.stacksize += STACKINCREMENT;}*s.top++ = e;return true;
}bool pop(SqStack &s, ElemType &e)
{if (s.top == s.base) return false;e = *--s.top;return true;
}void vis(ElemType a)
{cout << a << " ";
}void stackTraverse(SqStack s, void(*visit)(ElemType))
{ElemType *q = s.base;while (q!=s.top){visit(*q);q++;}
}int main()
{SqStack s;initStack(s);int n;int a;cin >> n;for (int i = 0; i < n; i++){cin >> a;push(s, a);}getTop(s, a);cout << "a = "<<a << endl;stackTraverse(s, vis);cout << endl;pop(s, a);pop(s, a);stackTraverse(s, vis);return 0;
}