资源描述
栈实验
理学院 信息与计算科学 班级: 学号: 姓名:
一、目的
1、掌握栈的各种基本操作。
2、掌握基本操作在具体应用中的运用。
3、掌握程序设计的各种调试手段。
二、实验内容
从键盘中接收字符,如果该字符与栈顶元素相同,则弹出栈顶元素,否者压入栈。如果接收的字符为‘$’则停止输入。要求先建立一个空栈。
三、实验课时
2学时
四、程序(包括源代码,输入,输出结果)
#include<stdio.h>
#include<stdlib.h>
#define Stack_Size 10
typedef struct{
char elem[Stack_Size];
int top;
}SeqStack;
void InitStack(SeqStack *S){
S->top=-1;
}
int isEmpty(SeqStack *S){
if(S->top==-1)
return(1);
else
return(0);
}
int push(SeqStack *S,char x){
if(S->top==Stack_Size-1) return(0);
S->top++;
S->elem[S->top]=x;
return(1);
}
int pop(SeqStack *S,char *x){
if(S->top==-1) return(0);
*x=S->elem[S->top];
S->top--;
return(1);
}
char GetTop(SeqStack *S){
char x;
if(S->top==-1) return(0);
else{
x=S->elem[S->top];
return(x);
}
}
int main(){
SeqStack S;
InitStack(&S);
char a;
char b;
int flag=1;
int tf;
while(flag){
a=getchar();
if(a!='$'){
if(a==GetTop(&S)&&!isEmpty(&S)){
tf=pop(&S,&b);
printf("%c出栈",b);
}
else{
tf=push(&S,a);
printf("%c入栈",a);
}
}
else{
flag=0;
}
}
return(1);
}
运行结果:
3 / 3
展开阅读全文