顺序栈
- 栈分为顺序栈和链栈。
- 顺序栈用数组存数据,整型指向栈顶。
- 特点就是先入先出原则。
- 栈在逻辑上是线性结构。
代码收获
- 出栈需要个元素获取出栈的数据,实际并没有把此数据从栈顶拿走。
- 操作上采用传地址的方式把出栈的值传给*地址。
- 初始化思路跟线性表顺序存储一样。
# include <stdio.h>
# include <stdlib.h>
#define MAXSIZE 100
typedef struct Stack{
int top;
char ele[MAXSIZE];
}stack,*stackp;
void InitialStack(stackp* ST){
*ST=(stackp)malloc(sizeof(stack));
(*ST)->top = -1;
}
int PushStack(stackp ST){
printf("输入需要插入的元素,按$退出\n");
int flag = 1;
while(flag){
char c;
c = getchar();
if(c!='$'){
if(ST->top+1==MAXSIZE){
printf("满栈!\n");
return 1;
}else{
ST->ele[(ST->top)+1]=c;
ST->top+=1;
}
} else{
flag = 0;
}
}getchar();
return 0;
}
int PopStack(stackp ST,char *x){
if (ST->top==-1){
printf("栈空\n");
return 1;}
else{
*x=ST->ele[ST->top];
ST->top--;
return 0;}
}
void PrintStack(stackp ST){
int mov=ST->top;
printf("栈内元素为\n");
for(;mov>-1;mov--){
printf("%c",ST->ele[mov]);
}
}
void main(){
stackp ST;
InitialStack(&ST);
PushStack(ST);
PrintStack(ST);
char x;
PopStack(ST,&x);
printf ("出栈元素为%c\n",x);
PrintStack(ST);
}