/*下午打球去了,虐菜了*/
<pre name="code" class="cpp">#ifndef _MATCH_H_ #define _MATCH_H_ #include<iostream> #include<string.h> #include<assert.h> using namespace std; typedef char ElemType; #define STACK_INIT_SIZE 50 typedef struct Stack { ElemType *base; int top; int stacksize; int capacity; }Stack; void InitStack(Stack *st); bool IsEmpty(Stack *st); bool IsFull(Stack *st); bool Push(Stack *st,ElemType x); bool Pop(Stack *st); //ElemType GetTop(Stack *st,ElemType *x); ElemType GetTop(Stack *stack); #endif
#include"match.h" void InitStack(Stack *st) { st->base = (ElemType *)malloc(sizeof(ElemType)*STACK_INIT_SIZE); assert(st->base != NULL); st->capacity = STACK_INIT_SIZE; st->top = 0; } bool IsFull(Stack *st) { return st->top >= st->capacity; } bool IsEmpty(Stack *st) { return st->top == 0; } bool Push(Stack *st, ElemType x) { if(IsFull(st)) { cout<<"栈已满,"<<x<<"不能入栈!"<<endl; return false; } st->base[st->top++] = x; return true; } bool Pop(Stack *st) { if(IsEmpty(st)) { cout<<"栈已空,不能出栈!"<<endl; return false; } st->top--; return true; } /*ElemType GetTop(Stack *st,ElemType *x) { if(IsEmpty(st)) { cout<<"栈为空:"<<endl; return false; } *x = st->base[--st->top];// *x = st->base[st->top--]; 效果是一样的吗? // cout<<"栈顶是:"<<*x<<endl;//不必要的输出 return *x; } */ ElemType GetTop(Stack *stack) { if(IsEmpty(stack)) { cout<<"栈空!"<<endl; } return stack->base[stack->top-1]; }
#include"match.h" void main() { Stack st; char str[1000]; ElemType item; 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, &item) != '[') if(IsEmpty(&st)||GetTop(&st ) != '[') flag = 0; else Pop(&st); } else if(str[i] == ')') { // if(IsEmpty(&st)||GetTop(&st,&item) != '(') if(IsEmpty(&st)||GetTop(&st ) != '(') flag = 0; else Pop(&st); } else if(str[i] == '}') { //if(IsEmpty(&st)||GetTop(&st, &item) != '{') if(IsEmpty(&st)||GetTop(&st ) != '{') flag = 0; else Pop(&st); } i++; } if(!IsEmpty(&st)) { flag = 0; } if(flag == 1) cout<<" 括号匹配 "<<endl; else { cout<< "括号不匹配"<<endl; } }
<img src="http://img.blog.csdn.net/20150516005559696?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvZnVqaW5sb25nNTIw/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" />
时间: 2024-10-10 15:22:13