#include <stdio.h>
#include <stdlib.h>
#define Stack_Size 50
typedef struct {
//用来存放栈中元素的一维数组
int elem[Stack_Size];
//用来存放栈顶元素的下标,top为-1表示空栈
int top;
}SeqStack;
//创建空栈
SeqStack InitStack(){
//构造一个空栈S
SeqStack stack;
stack.top= -1;
}
//创建一个栈
SeqStack CreatStack(){
printf("输入数字,输入-1表示结束\n");
SeqStack stack;
stack.top= -1;
int temp;
while (1) {
scanf("%d",&temp);
if (temp==-1){
return stack;
}
stack.top++;
stack.elem[stack.top]=temp;
}
}
//入栈
int Push(SeqStack * S, int x){
//栈已满
if(S->top== Stack_Size-1) {
return 0;
}
S->top++;
S->elem[S->top]=x;
return 1;
}
//出栈
int Pop(SeqStack* S){
//栈为空
if(S->top==-1) {
return 0;
}
//修改栈顶指针
int x = S->elem[S->top];
S->top--;
return x;
}
//取栈顶元素
int GetTop(SeqStack* S) {
//将栈S的栈顶元素弹出,放到x所指的存储空间中,但栈顶指针保持不变
if(S->top==-1) /*栈为空*/ {
return 0;
}
int x = S->elem[S->top];
return x;
}
int main(int argc, char const *argv[])
{
SeqStack stack;
stack = InitStack();
Push(&stack,10);
Push(&stack,20);
int i = GetTop(&stack);
printf("栈顶元素是%d\n",i);
Pop(&stack);
i = GetTop(&stack);
printf("栈顶元素是%d\n",i);
return 0;
}
C语言实现顺序栈
最新推荐文章于 2022-11-10 00:46:09 发布