栈是一个种特殊的线性表,它只能在栈顶进行插入和删除操作,它实现的是一种后进先出(LIFO)的策略。
可以用数组来作为栈,插入操作称为push,删除操作称为pop,栈有个属性top[S],它指向最近插入的元素,称为栈顶,例如栈S包含元素S[1..top[S]],其中S[1]是栈底元素,S[top[S]]是栈顶元素。
当top[S]=0时,栈不包含任何元素,称为空栈,判断空栈过程如下:
STACK-EMPTY(S)
if top[S] = 0
then return TRUE
else return FALSE
c代码为:
int stack_empty(int S[])
{
if (top == 0) {
return 1;
}
return 0;
}
压栈过程如下:
PUSH(S, x)
top[S] <-- top[S]+1
S[top[S]] <-- x
c代码为:
void push(int S[], int x)
{
S[top++] = x;
}
出栈过程如下:
POP(S)
if STACK-EMPTY(S)
then error "underflow"
else top[S] <-- top[S]-1
return S[top[S]+1]
c代码为:
int pop(int S[])
{
if (stack_empty(S)) {
printf("underflow.
");
} else {
return S[top--];
}
}