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
#include <stdio.h> #include <stdlib.h> #include "stack.h" #define FALSE 0 #define BUF_SIZE 100 int check_parenthesis(char *s) { clear_stack(); char c; while (c = *s++) { if (c == '(' || c == '{' || c == '[') { if (!can_push()) exit(1); switch (c) { case '(': c = ')'; break; case '{': c = '}'; break; case '[': c = ']'; break; } push_val(c); } else if (c == ')' || c == '}' || c == ']') { if (!can_pop()) return FALSE; if (pop_val() != c) return FALSE; } } return !can_pop(); } void main() { char buf[BUF_SIZE]; while (1) { printf("input string > "); fgets(buf, BUF_SIZE, stdin); if (buf[0] == '\n') break; if (check_parenthesis(buf)) printf("parenthesis is correct.\n"); else printf("parenthesis is incorrect.\n"); } }