括號配對是最基本的棧的問題,它是棧入門的經典題目,思路是,如果是左括號直接進棧,如果是右括號,這時就要比較棧頂的元素與他是否匹配,如果匹配則出棧,否則進棧,下面是代碼的實現:
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 }
?