标签:style blog color io ar 问题 div 代码 log
括号配对是最基本的栈的问题,它是栈入门的经典题目,思路是,如果是左括号直接进栈,如果是右括号,这时就要比较栈顶的元素与他是否匹配,如果匹配则出栈,否则进栈,下面是代码的实现:
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 }
标签:style blog color io ar 问题 div 代码 log
原文地址:http://www.cnblogs.com/Howe-Young/p/3930914.html