首页 > 代码库 > NYOJ2括号配对问题

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             else26                 top = push_stack(top, ch[i]);//否则压栈27             i ++;28         }29         if(top -> ch == 0)//判断栈是否为空30             printf("Yes\n");31         else32             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     else60     {61         node = top;62         top = top -> next;63         free(node);64         return top;65 66     }67 68 }

 

NYOJ2括号配对问题