-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.c
84 lines (73 loc) · 1.74 KB
/
stack.c
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
#include <stdio.h>
#define STACK_SIZE 20
/* external variables */
int contents[STACK_SIZE];
int top = 0;
void make_empty() {
top=0;
}
int is_full() {
return top==STACK_SIZE;
}
void push(int i)
{
if(is_full())
printf("stack overflow. The imput is not balanced.");
else
contents[top++]=i;
}
int is_empty() {
return top ==0;
}
int pop(void)
{
if(is_empty())
return -1; //-1 means stack empty
else
return contents[--top];
}
int main(void) {
int c, i, j, tmp, isbalanced;
do {
j = 0;
printf("Enter your input that contains parenthesis or Q to quit:\n");
while ((c = getchar()) != '\n') {
j++;
tmp = c;
if(c == '(' || c == '<' || c == '[' || c == '{') {
push(c);
}
if(c == ')' || c == '>' || c == ']' || c == '}') {
if(c == ')' && pop() == '(') {
continue;
}
else if(c == '>' && pop() == '<') {
continue;
}
else if(c == ']' && pop() == '[') {
continue;
}
else if(c == '}' && pop() == '{') {
continue;
}
else {
top++;
isbalanced = 0;
}
}
}
if(tmp == 'Q' && j ==1)
return 0;
if(top == 0)
isbalanced = 1;
else
isbalanced = 0;
if(isbalanced == 1)
printf("The input is balanced.\n");
else
printf("The input is not balanced.\n");
make_empty();
}
while (i >= 0);
return 0;
}