NYOJ2括号配对问题

括号配对是最基本的栈的问题,它是栈入门的经典题目,思路是,如果是左括号直接进栈,如果是右括号,这时就要比较栈顶的元素与他是否匹配,如果匹配则出栈,否则进栈,下面是代码的实现:

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 typedef struct stack{//定义栈来存储括号
 4     char ch;
 5     struct stack *next;
 6 }link_stack;
 7 link_stack * init_link_stack();
 8 link_stack * push_stack(link_stack *top, char ch);
 9 link_stack * pop_stack(link_stack *top);
10 int main()
11 {
12     int n;
13     scanf("%d", &n);
14     getchar();
15     while(n --)
16     {
17         link_stack * top;
18         top = init_link_stack();//初始化top指针
19         char ch[10001];
20         scanf("%s", ch); int i = 0;
21         while(ch[i] != '\0')//判断读到结束符
22         {
23             if(((ch[i] == ']') && (top -> ch == '['))||((ch[i] == ')') &&(top -> ch == '(')))//如果将要进栈的是右括号,判断栈顶元素是否为左括号,如果是就弹出
24                 top = pop_stack(top);
25             else
26                 top = push_stack(top, ch[i]);//否则压栈
27             i ++;
28         }
29         if(top -> ch == '0')//判断栈是否为空
30             printf("Yes\n");
31         else
32             printf("No\n");
33     }
34     return 0;
35 }
36 
37 link_stack * init_link_stack()//初始化栈函数
38 {
39     link_stack *node;
40     node = (link_stack *) malloc(sizeof(link_stack));
41     node -> next = NULL;
42     node ->ch = '0';
43     return node;
44 }
45 link_stack * push_stack(link_stack *top, char ch)//入栈函数
46 {
47     link_stack *node;
48     node = init_link_stack();
49     node -> ch = ch;
50     node -> next = top;
51     top = node;
52     return top;
53 }
54 link_stack * pop_stack(link_stack *top)//出栈函数
55 {
56     link_stack *node;
57     if(top -> next == NULL)
58         return top;
59     else
60     {
61         node = top;
62         top = top -> next;
63         free(node);
64         return top;
65 
66     }
67 
68 }

 

转载于:https://www.cnblogs.com/Howe-Young/p/3930914.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值