括弧匹配問題 (c++)

來源:互聯網
上載者:User
文章目錄
  •  實驗題目(共10題, 第7題)
 實驗題目(共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 }
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.