m0_69473531 2022-09-27 00:08 采纳率: 72.2%
浏览 637
已结题

C语言 设计一个算法判别一个算术表达式的圆括号是否正确配对

输入形式:一个以@为结尾的算术表达式。
输出形式:若配对则输出圆括号的对数;否则输出no
样例输入:(a+b)/(c+d)@ 输出:2
#include <stdio.h>
#include <stdlib.h>
#define max 100
typedef struct sta
{
char data[max];
int top;
} stack;
stack* init()
{
stack s=(stack)malloc(sizeof(stack));
s->top=-1;
return s;
}
int empty(stack s)
{
if(s->top==-1)
return 1;
else return 0;
}
int push(stack
s,char x)
{
if(s->top==max-1) return -1;
else
{
s->top++;
s->data[s->top]=x;
return 1;
}
}
int pop(stack* s,char *x)
{
if(empty(s)) return 0;
else
{
*x=s->data[s->top];
s->top--;
return 1;
}
}
int result()
{
char x;int flag=1,flag1=1;
stack *s=init();
while((x=getchar())!=EOF)
{
if(x=='(')
flag=push(s,x);
if(x==')')
flag1=pop(s,&x);
}
if(empty(s)&&flag==1&&flag1==1) return 1;
else return -1;
}
int main()
{
int flag;
flag=result();
if(flag==1)
printf("1");
else printf("0");
return 0;
}

  • 写回答

2条回答 默认 最新

  • _GX_ 2022-09-29 21:21
    关注
    #include <stdio.h>
    
    int main()
    {
        char ch;
        int n = 0, depth = 0, matched = 1;
        while (((ch = getchar()) != EOF) && (ch != '@'))
        {
            if (ch == '(')
            {
                n++;
                depth++;
            }
            else if (ch == ')')
            {
                if (depth == 0)
                {
                    matched = 0;
                    break;
                }
                else
                {
                    depth--;
                }
            }
        }
        if (depth != 0)
            matched = 0;
        if (matched)
            printf("%d\n", n);
        else
            printf("no\n");
        return 0;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 请回答用户的提问 10月30日
  • 已结题 (查看结题原因) 10月16日
  • 已采纳回答 10月16日
  • 修改了问题 9月27日
  • 展开全部

悬赏问题

  • ¥170 如图所示配置eNSP
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥15 键盘指令混乱情况下的启动盘系统重装