-
Notifications
You must be signed in to change notification settings - Fork 119
/
20.c
83 lines (75 loc) · 1.68 KB
/
20.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int bool;
#define true 1
#define false 0
struct Node {
char val;
struct Node *next;
};
void push(struct Node** top_pt, char new_data)
{
struct Node *new_node = (struct Node *)malloc(sizeof(struct Node));
new_node->val = new_data;
new_node->next = *top_pt;
*top_pt = new_node;
}
int pop(struct Node** top_pt)
{
if (*top_pt == NULL)
{
printf("stack overflow\n");
exit(0);
}
struct Node *top = *top_pt;
char res = top->val;
*top_pt = top->next;
free(top);
return res;
}
bool isValid(char *s) {
struct Node *stack = NULL;
int i;
int len = strlen(s);
for (i = 0; i < len; i++) {
if (s[i] == '(' || s[i] == '[' || s[i] == '{') {
push(&stack, s[i]);
}
else {
if (stack == NULL)
return false;
char top = pop(&stack);
if (s[i] == ')') {
if (top != '(') return false;
}
else if (s[i] == ']'){
if (top != '[') return false;
}
else if (s[i] == '}'){
if (top != '{') return false;
}
}
}
if (stack == NULL)
return true;
else
return false;
}
void print_stack(struct Node** top_pt)
{
struct Node *t = *top_pt;
while (t != NULL)
{
struct Node *tmp_node = t;
printf("%c ", tmp_node->val);
t = tmp_node->next;
}
printf("\n");
}
int main()
{
char s[] = "]";
printf("%d\n", isValid(s));
return 0;
}