//栈的顺序存储
#include<stdio.h>
#include<stdbool.h>
#define MaxSize 50
#define ElemType char
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
//栈的初始化
void InitStack(SqStack *S){
(S->top) = -1;
}
//栈的判空操作
bool StackEmpty(SqStack S){
if((S.top) == -1)
return true;
else
return false;
}
//进栈
bool Push(SqStack *S,ElemType x){
if((S->top) == (MaxSize-1))
return false;
(S->data)[++(S->top)] = x;
return true;
}
//出栈
bool Pop(SqStack *S,ElemType *x){
if(S->top == -1)
return false;
*x = (S->data)[(S->top)--];
return true;
}
//读取栈顶元素
bool getTop(SqStack S,ElemType *s){
if(S.top == -1)
return false;
*s = S.data[S.top];
return true;
}
//读取栈的所有元素
void StackPrint(SqStack S){
char x;
if(S.top == -1)
return false;
while(!StackEmpty(S)){
Pop(&S,&x);
printf("%c ",x);
}
printf("\n");
}
int main(){
SqStack s;
InitStack(&s);
int n;
char c,node;
printf("请输入要插入的栈的元素:");
do{
scanf("%c",&node);
//printf("%c",node);
Push(&s,node);
}while(c = getchar() == ' ');
printf("该栈中的元素为\n");
StackPrint(s);
printf("栈顶元素为:");
getTop(s,&c);
printf("%c",c);
printf("\n************************************\n因为在栈的输出中已经用到所有操作,所以不作另外编写\n*************************************");
}
数据结构之栈的基本操作(c语言版)
最新推荐文章于 2023-07-28 23:43:45 发布