栈的定义:
栈又称堆栈,是一种特殊的线性表,限制:先进后出
允许插入和删除的一端叫做变化的一端 称为栈顶, 栈顶元素 栈底。
比如把子弹压入弹夹,里面的子弹就是先进后出。
栈的顺序存储结构 简称顺序栈,它是利用一组地址连续的存储单元依次存放自栈底到栈顶的数据元素。
顺序栈的定义及相关操作。
#include<stdio.h>
#define MAXLEN 10
typedef int elementtype;
typedef struct//栈的顺序存储结构的定义
{
elementtype element[MAXLEN];/*存放栈元素的数组*/
int top;
}SqStack;
SqStack InitStack_Sq(){ /*建立一个空栈*/
SqStack s;
s.top =-1;
return (s);
}
/*取栈顶元素 若栈s非空 用*x 返回栈顶元素*/
int GetTop_sq(SqStack *s,elementtype *x){
if(s->top==-1)
return (0);
else{
* x = s->element[s->top];
return (1);
}
}
int Push_sq(SqStack *s,elementtype x){/*进栈 若s未满,将元素x进栈*/
if(s->top==MAXLEN-1)
return(0);
s->top++; //将top下移一位
s->element[s->top] = x;
return(1);
}
int Pop_sq(SqStack * s,elementtype *x){
if(s->top==-1)
return (0);
* x = s->element[s->top];//取栈顶元素
s->top--;
return (1);
}
int Empty_sq(SqStack *s){
return(s->top==-1);
}
void print(SqStack s){/*输出栈元素*/
int i;
if(s.top!=-1){
printf("output the element of stack: ");
for(i=0;i<=s.top;i++){
printf("%d ",s.element[i]);
}
}else
printf("the stack is empty");
}
main(){
SqStack stack;
int i ;
elementtype y;
elementtype z;
stack = InitStack_Sq();
if(Empty_sq(&stack))
printf("\n The stack is empty!");
else
printf("\n The stack is not empty!");
printf("\n push 5 element to stack: ");
for(i=1;i<=5;i++){/*入栈五个元素*/
scanf("%d",&y);
Push_sq(&stack,y);
}
print(stack);
GetTop_sq(&stack,&z);
printf("Element of top is: %d \n",z);
printf("Pop 3 element form stack: ");
for(i=1;i<=3;i++){
Pop_sq(&stack,&z);
printf("%d",z);
}
printf("\n");
print(stack);/*出栈三个元素后的栈*/
}
对于顺序栈来说,入栈时 必须首先判断栈是否满了,若栈满,不能入栈,出栈必须首先判断栈是否为空,若栈空,则不能出栈