数据结构习题——7表达式括号匹配

time_limit

3000MS

memory_limit

10000KB

description

假设一个算术表达式中可以包含三种括号:圆括号“(”和“)”、方括号“[”和“]”和花括号“{”和“}”,且这三种括号可按任意的次序嵌套使用(如:…[…{…}…[…]…]…[…]…(…)…)。编写判别给定表达式中所含括号是否正确配对出现的程序(已知表达式已存入数据元素为字符的顺序表中)。

input

输入算术表达式,换行结束。

output

若给定表达式中所含括号正确配对,则输出yes,否则输出no。

sample_input

[5+(6-3)]-(2+3)]

sample_output

no

#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
#define N 200
typedef struct Stack{
    Elemtype elem[N];
    int top;
}SeqStack,*PSeqStack;

PSeqStack Init_stack()
{
    PSeqStack pstack;
    pstack=(PSeqStack)malloc(sizeof(SeqStack));
    if(pstack==NULL)printf("Out of space!\n");
    else pstack->top=-1;
    return pstack;
}

void push(PSeqStack pstack,Elemtype x)
{
    if(pstack->top>=N-1)printf("Overflow!");
    else{
		pstack->top++;
        pstack->elem[pstack->top]=x;
    }
}
int isnull(PSeqStack pstack)
{
    return (pstack->top==-1);
}
Elemtype pop(PSeqStack pstack)
{
    Elemtype x;
    x=pstack->elem[pstack->top];
    pstack->top--;
    return x;
}
Elemtype get(PSeqStack pstack)
{
    Elemtype x;
    x=pstack->elem[pstack->top];
    return x;
}
int main()
{
    char s[100],t;
    int i=0;
    PSeqStack pstack;
    pstack=Init_stack();
    gets(s);
    while(s[i]!='\0'){
        if(s[i]==')'||s[i]==']'||s[i]=='}'||s[i]=='('||s[i]=='['||s[i]=='{'){
            if(s[i]=='('||s[i]=='['||s[i]=='{')
                push(pstack,s[i]);
            else{
                if(isnull(pstack)){printf("no\n");break;}
                t=get(pstack);
                if(s[i]==t+1||s[i]==t+2){
                    pop(pstack);
                }
                else {printf("no\n");break;}
            }
        }
        i++;
    }
    if(s[i]=='\0'&&isnull(pstack))printf("yes\n");
    //printf("Hello world!\n");
    return 0;
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值