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 94
| #include <stdio.h> #define Maxsize 10
typedef struct { char data[Maxsize]; int top; }SqStack;
void InitStack(SqStack& S) { S.top = -1; }
bool isEmpty(SqStack S) { return S.top == -1; }
bool Push(SqStack& S, char element) { if (S.top == Maxsize - 1) { return false; } S.data[++S.top] = element; return true; }
int Pop(SqStack& S) { if (S.top == -1) { return -1; } return S.data[S.top--]; }
int GetTop(SqStack S) { if (S.top == -1) { return -1; } return S.data[S.top]; }
void ShowStack(SqStack S) { for (int i = 0; i <= S.top; i++) { printf("%d ", S.data[i]); } }
void bracketCheck(char str[], int length) { SqStack S; InitStack(S); for (int i = 0; i < length; i++) { if (str[i] == '(' || str[i] == '[' || str[i] == '{') { Push(S, str[i]); } else { if (isEmpty(S)) { printf("栈为空"); } else { char topElement = Pop(S); if (str[i] == ')' && topElement != '(') { printf("匹配不正确!"); } if (str[i] == ']' && topElement != '[') { printf("匹配不正确!"); } if (str[i] == '}' && topElement != '{') { printf("匹配不正确!"); } } } } if (isEmpty(S)) { printf("匹配成功!"); } else { printf("匹配失败!"); } }
int main() { char str_char[] = { '{', '{', '[', '[', ']', ']', '(', ')', '(', ')', '}', '}' }; bracketCheck(str_char, (sizeof(str_char)/sizeof(str_char[0]))); return 0; }
|