实验3:顺序栈的基本操作
实验目的:
1、掌握顺序栈的存储结构
2、实现顺序栈的基本操作
实验内容:
判断一个表达式中括号“(”与“)”、“[”与“]”、“{ ”与“}”是否匹配。若匹配,则返回1;否则返回0。
实验数据:
- {(1+2/[3])}
- {[}]2+4()
实验要求:
- 代码完整
- 程序的运行结果
实验心得(实验收获,不足):
提示:
本实验是在顺序栈的基本上完成的,请写出顺序栈的定义和关于顺序栈的七种操作。
再写上int Match(ElemType *exps)函数。
main函数只需要定义一个字符数组表示表达式,在调用Match函数即可。
char s[80];
gets(str);
Match(str)
要想看到结果,请注意Match函数的返回值,设计代码!
加油!!!
#include<stdio.h>
#include<stdlib.h>
#define INITSIZE 100
typedef char ElemType;
typedef struct
{
ElemType *base;
int top;
int stacksize;
} SeqStack;
void InitStack(SeqStack *s){
s->base=(ElemType *)malloc(INITSIZE*sizeof(ElemType));
s->top=0;
s->stacksize=INITSIZE;
}
int Push(SeqStack *s,ElemType x){
if(s->top>=s->stacksize) {
s->base=(ElemType *)realloc(s->base,(s->stacksize+1)*sizeof(ElemType));
if(!s->base) return 0;
s->stacksize++;
}
s->base[s->top++]=x;
return 1;
}
int Pop(SeqStack *s,ElemType *e){
if(s->top==0) return 0;
*e=s->base[--s->top];
return 0;
}
int EmptyStack(SeqStack *s){
if(s->top==0) return 1;
return 0;
}
int Match(ElemType *exps){
SeqStack s;int i=0;
ElemType x;
int a[6]={0};
InitStack(&s);
while(exps[i]!='\0')
{Push(&s,exps[i]);i++;}
while(!EmptyStack(&s)){
Pop(&s,&x);
switch(x){
case '(':a[0]++;break;
case ')':a[1]++;break;
case '[':a[2]++;break;
case ']':a[3]++;break;
case '{':a[4]++;break;
case '}':a[5]++;break;
}
}
if((a[0]+a[1])%2==0&&(a[2]+a[3])%2==0&&(a[4]+a[5])%2==0)
return 1;
return 0;
}
int main (void){
char str[80];
gets(str);
if(Match(str))
printf("匹配!");
else
printf("匹配!");
return 0;
}
实验结果:
(1)
(2)
实验心得:熟练掌握核心代码,要懂得灵活变通,深入思考为什么代码能够运行!