循序栈的基本操作
栏目分类:计算机知识 发布日期:2020-01-28 浏览次数:次
循序栈的基本操作
首先采用顺序存储结构的栈称为:顺序栈
一 栈的定义
-
#define M 100 //定义栈可能的最大长度 -
typedef int datatype; //代表了数据类型 -
typedef struct -
{ -
datatype data[M]; //栈占用的数组空间 -
int top; //栈顶指针指向栈顶元素在数组中的位置 -
}stack;
二 置空栈 创建一个空的顺序栈s,即栈的初始化
-
void initstack(stack *s) -
{ -
s->top=-1; -
}
三 进栈 首先让栈顶指针top加1,然后将新元素x插入栈顶指针指向的位置
-
int push(stack *s,datatype x) -
{ -
if(s->top>=M-1) //栈存储空间满,不能进栈 -
{ -
printf("overflow "); -
return 0; -
} -
s->top++; //移动栈顶元素 -
s->data[s->top]=x; //元素x进栈 -
return 1; -
}
四 出栈 先将栈顶元素赋给一个变量,然后将栈顶指针top-1
-
datatype pop(stack *s) -
{ -
datatype x; -
if(s->top<0) //栈空,不能出栈 -
{ -
printf("underflow "); -
exit(0); -
} -
x=s->data[s->top]; //保存栈顶元素到变量x -
s->top--; //移动栈顶指针 -
return x; //返回栈顶元素 -
}
本文由IT教学网整理发布,转载请注明出处:http://www.itjx.com/rumen/jisuanji/565.html
