一栈的定义
栈是限定在表尾一端进行插入或插入的线性表,在栈中允许插入和删除操作的一端称为栈顶,另一端称为栈底。
二顺序栈的基本运算
#define TRUE 1
#define FALSE 0
#define MAXSIZE 100 /*栈的最大元素*/
typedef int elemtype;
typedef struct
{
elemtype stack[MAXSIZE];
int top;
}sqstack;
(1)初始化栈
void initStack(sqstack *s) /*初始化栈*/
{
s->top=-1;
}
(2)进栈
int push(sqstack *s,elemtype x) /*进栈操作*/
{
if(s->top>=MAXSIZE-1)/*栈溢出情况*/
{
printf("Stack Overflow!");
return (FALSE);
}
else
{
s->top++;
s->stack[s->top]=x;
return (TRUE);
}
}
(3)出栈
int pop(sqstack *s) /*出栈操作*/
{
if(s->top<0) /*栈空情况*/
{
printf("stack unerflow!");
return(FALSE);
}
else
s->top--;
return(s->stack[s->top+1]);
}
(4)栈的遍历
void display_stack(sqstack *s) /*遍历栈并输出*/
{
int i;
printf("The elements in stack are ");
for(i=s->top;i>=0;i--)
printf(" %d ",s->stack[i]); printf("/n");
}
(5)取栈顶元素
int gettop(sqstack *s)
{
if(s->top<0)
{
printf("Stack is empty");
return (FALSE);
}
else
return(s->stack[s->top]);
}
函数调用实例
int main()
{
sqstack *p=(sqstack*)malloc(sizeof(sqstack));
initStack(p);
push(p,1);
push(p,2);
push(p,3);
display_stack(p);
printf("The top element in stack is %d /n",gettop(p));
pop(p);
display_stack(p);
printf("The top element in stack is %d /n",gettop(p));
return 0;
}