赞
踩
学习笔记
- #include<stdio.h>
- #include<stdlib.h>
- #include<string.h>
-
- #define MaxSize 10
- typedef struct{
- char data[MaxSize];
- int top;
- }SqStack;
-
- //初始化栈
- void InitStack(SqStack &S){
- S.top = 0;
- }
-
- //判断栈是否为空
- bool StackEmpty(SqStack S){
- if (S.top == 0) return true;
- return false;
- }
-
- //新元素入栈
- bool Push(SqStack &S,char x){
- if (S.top > MaxSize) return false;
- S.data[S.top] = x;
- printf("此时入栈的为: %c\n",x);
- S.top++;
- return true;
- }
-
- //栈顶元素出栈
- bool Pop(SqStack &S,char &x) {
- if (S.top == 0) return false;
- x = S.data[S.top-1];
- printf("此时出栈的为: %c\n",x);
- S.top--;
- return true;
- }
-
- bool 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(StackEmpty(S)) return false;
-
- char topelem;
- Pop(S,topelem);
- if(str[i] == ')' && topelem != '(')
- {
- printf("匹配失败!\n");
- return false;
- }
- if(str[i] == ']' && topelem != '[')
- {
- printf("匹配失败!\n");
- return false;
- }
- if(str[i] == '}' && topelem != '{')
- {
- printf("匹配失败!\n");
- return false;
- }
- printf("这一对括号为:%c %c\n",topelem,str[i]);
- }
- }
- return StackEmpty;
- }
-
- int main(){
- char str[] = "{[([])]}";
- int length = strlen(str);
- bracketCheck(str,length);
- return 0;
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。