利用栈的结构性质实现括号匹配
(今天被自己玩死了,‘=‘&&‘==‘小问题坑死人不偿命)
Matbr.h
#ifndef _MATCH_H_ #define _MATCH_H_ #include<iostream> #include<string.h> #include<assert.h> using namespace std; typedef char ElemType; #define STACK_MAX_SIZE 100 typedef struct Stack { ElemType *base; int top; int stacksize; int capacity; }Stack; void InitStack(Stack *stack); bool isfull(Stack *stack); bool isempty(Stack *stack); bool push(Stack *stack,ElemType x); bool pop(Stack *stack); ElemType GetTop(Stack *stack); #endif //_MATCH_H_
Matbr.cpp
#include"Matbr.h" void InitStack(Stack *stack) { stack->base = (ElemType *)malloc(sizeof(ElemType)*STACK_MAX_SIZE); assert(stack->base != NULL); stack->top = 0; stack->capacity = STACK_MAX_SIZE; stack->stacksize = 0; } bool isfull(Stack *stack) { return stack->stacksize == stack->capacity; } bool isempty(Stack *stack) { return stack->stacksize == 0; } bool push(Stack *stack,ElemType x) { if(isfull(stack)) return false; stack->base[stack->top++] = x; stack->stacksize++; return true; } bool pop(Stack *stack) { if(isempty(stack)) return false; stack->base[stack->top--]; stack->stacksize--; return true; } ElemType GetTop(Stack *stack) { if(isempty(stack)) { cout<<"栈空!"<<endl; } return stack->base[stack->top-1]; }
man.cpp
#include"Matbr.h" void main (void) { Stack st; char str[2015]; InitStack(&st); cin>>str; int len = strlen(str); int i = 0; int flag = 1; while(i<len) { if(str[i] == '(' || str[i] == '{' ||str[i] == '[') push(&st,str[i]); else if(str[i] == ')') { if(isempty(&st) || GetTop(&st) != '(' ) flag = 0; else pop(&st); } else if(str[i] == ']') { if(isempty(&st) || GetTop(&st) != '[' ) flag = 0; else pop(&st); } else if(str[i] == '}') { if(isempty(&st) || GetTop(&st) != '{' ) flag = 0; else pop(&st); } i++; } if(!isempty(&st)) { flag = 0; } if(flag == 1) cout<<"Matching brackets(匹配)"<<endl;//匹配 else { cout<<"The brackets do not match(不匹配)"<<endl;//不匹配 } }
时间: 2024-10-05 08:23:01