-
Notifications
You must be signed in to change notification settings - Fork 0
/
bracket.cpp
93 lines (91 loc) · 1.61 KB
/
bracket.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <iostream>
#include <string>
using namespace std;
const int MAX = 100;
typedef struct
{
char data[MAX];
int top;
}Stack;
void initStack(Stack &S)
{
S.top = 0;
}
bool empty(Stack &S)
{
return !S.top ? true : false;
}
void push(Stack &S, char val)
{
S.top++;
S.data[S.top] = val;
}
bool pop(Stack &S, char *val)
{
if(empty(S))
{
cout << "the stack is empty!" << endl;
return false;
}
else
{
*val = S.data[S.top];
S.top--;
return true;
}
}
bool comp(char a, char b)
{
if(a == '(' && b == ')')
return true;
else if(a == '[' && b == ']')
return true;
else if(a == '{' && b == '}')
return true;
else
return false;
}
void bracket(Stack S)
{
string brac;
char ch;
cout << "please input the brackets: ";
cin >> brac;
for(string::size_type pos = 0; pos!=brac.size(); pos++)
{
switch(brac[pos])
{
case '(':
case '[':
case '{':
push(S, brac[pos]);
break;
case ')':
case ']':
case '}':
if(empty(S))
{
cout << "matching failed!" << endl;
return;
}
pop(S, &ch);
if(!comp(ch, brac[pos]))
{
cout << "matching failed!" << endl;
return;
}
break;
}
}
if(empty(S))
cout << "success!" << endl;
else
cout << "matching failed!" << endl;
}
int main()
{
Stack S;
initStack(S);
bracket(S);
return 0;
}