顺序栈定义与操作
1. 结构定义(动态分配内存)
typedef struct StackNode
{
ElemType data;
struct StackNode* next;
}StackNode, *LinkStack;
2. 栈的初始化
bool InitStack(SqStack &S)
{
S.elem = (ElemType*) malloc(MAXSIZE * sizeof(ElemType));
if(!S.elem) exit(OVERFLOW);
S.stackSize = MAXSIZE;
S.top = -1;
return success;
}
3. 判断是否栈空
bool isEmpty(SqStack &S)
{
return (S.top == -1)? true : false;
}
4. 获取栈中元素个数
int StackLength(SqStack &S)
{
return S.top + 1;
}
5. 向栈中插入栈顶元素
bool Push(SqStack &S, ElemType e)
{
if(S.stackSize - 1 == S.top)
{
ElemType* newElem = (ElemType*) realloc(S.elem, (S.stackSize + INCREMENT) * sizeof(ElemType) );
if(!newElem) exit(OVERFLOW);
S.stackSize += INCREMENT;
S.elem = newElem;
}
S.elem[++S.top] = e;
return success;
}
6. 访问栈顶元素
bool GetTop(SqStack &S, ElemType &e)
{
if(S.top == -1) return failed;
e = S.elem[S.top];
return success;
}
7. 取出栈顶元素
bool Pop(SqStack &S, ElemType &e)
{
if(S.top == -1) return failed;
e = S.elem[S.top--];
return success;
}
8. 遍历顺序栈所有元素
void StackTraverse(SqStack S)
{
while(~S.top)
{
printf("%d\n", S.elem[S.top--]);
}
}