文章目錄
實驗題目(共10題, 第7題)
標題: |
括弧匹配問題 |
時 限: |
1000 ms |
記憶體限制: |
10000 K |
總時限: |
3000 ms |
描述: |
用順序儲存實現棧的初始化、入棧、出棧、取棧頂、判棧空操作。調用以上操作實現判斷從鍵盤輸入的括弧序列是否匹配。 |
輸入: |
括弧序列#(#為括弧輸入結束符號) |
輸出: |
匹配或不匹配 |
輸入範例: |
{[()]}# [{{}[(])}]# |
輸出範例: |
匹配 不匹配 |
提示: |
|
來源: |
View Code
1 #include<stdio.h>
2 #include<stdlib.h>
3
4 #define STACKINCRESE 100
5 #define STACK_IN 10
6 typedef struct
7 {
8 char *base;
9 char *top;
10 int stacksize;
11 }SqStack;
12
13 void Initstack(SqStack &s)
14 {
15 s.base=(char*)malloc(STACK_IN * sizeof(char));
16 if(!s.base) exit(1);
17 s.top=s.base;
18 s.stacksize=STACK_IN;
19 }
20
21 char Gettop(SqStack &s,char e)
22 {
23 e=*(s.top-1);
24 return e;
25 }
26
27 void Push(SqStack &s,char e)
28 {
29 if((s.top-s.base)>s.stacksize)
30 {
31 s.base=(char *)realloc(s.base,(s.stacksize+STACKINCRESE)*sizeof(char));
32 if(!s.base) exit(1);
33 s.top=s.base+s.stacksize;
34 s.stacksize=s.stacksize+STACKINCRESE;
35 }
36 *s.top++=e;
37 }
38
39 void Pop(SqStack &s,char e)
40 {
41 if(s.base==s.top) exit(1);
42 e=*--s.top;
43 }
44
45 int main(void)
46 {
47 SqStack s;
48 Initstack(s);
49 char a,e;
50 scanf("%c",&a);
51 Push(s,a);
52 scanf("%c",&a);
53 while(a!='#')
54 {
55 switch(a)
56 {
57 case']':
58 {
59 if(Gettop(s,e)!='[')
60 {
61 Push(s,a);
62 }
63 else Pop(s,e);
64 break;
65 }
66 case')':
67 {
68 if(Gettop(s,e)!='(')
69 {
70 Push(s,a);
71 }
72 else Pop(s,e);
73 break;
74 }
75 case'}':
76 {
77 if(Gettop(s,e)!='{')
78 {
79 Push(s,a);
80 }
81 else Pop(s,e);
82 break;
83 }
84 case'[':case'{':case'(':
85 {
86 Push(s,a);
87 break;
88 }
89 }
90 scanf("%c",&a);
91 }
92 if(s.base==s.top) printf("匹配");
93 else printf("不匹配");
94 return 0;
95 }