括号配对问题:
假设一个表达式中包含三种类型的括号:(),{ },【】,嵌套顺序任意
{ 【()()】 }
1 2 3 4 5 6 7 8
引入“期待的急迫程度”概念,例如当接受第一个括号 { ,则它期待与第8个 } 匹配,然而当接受到第二个 【 时,此时【最期待和第七个 】 匹配。
#ifndef _MATCH_H_ #define _MATCH_H_ #include<iostream> #include <malloc.h> #include <string.h> #include<assert.h>//断言 using namespace std; #define MAXLEN 100 typedef char ElemType; typedef struct node { ElemType data; struct node *next; }Node,*LinkStack; void InitStack(LinkStack *stack);//将链栈初始化 bool StackEmpty(LinkStack stack);//判断链栈是否为空 ElemType* GetTop(LinkStack stack,ElemType *e);//取栈顶元素 bool PushStack(LinkStack stack,ElemType e);//进栈操作 bool PopStack(LinkStack stack,ElemType *e);//出栈操作 int StackLength(LinkStack stack);//求表长操作 void DestroyStack(LinkStack stack);//销毁链表 bool Match(ElemType e,ElemType ch);//判断括号 #endif
#include "match.h" void InitStack(LinkStack *stack)//将链栈初始化 { if ((*stack = (LinkStack)malloc(sizeof(stack))) == NULL) { exit(-1); } (*stack)->next = NULL; } bool StackEmpty(LinkStack stack)//判断链栈是否为空 { if (NULL == stack->next) return true; else return false; } ElemType* GetTop(LinkStack stack,ElemType *e)//取栈顶元素 { Node *p = stack->next; if (!p) { return NULL; } *e = p->data; return e; } bool PushStack(LinkStack stack,ElemType e)//进栈操作 { Node*s = (Node *)malloc(sizeof(Node)); if (NULL == s) return false; s->data = e; s->next = stack->next; stack->next = s; return true; } bool PopStack(LinkStack stack,ElemType *e)//出栈操作 { Node *p = stack->next; if (StackEmpty(stack)) { cout << "EmptyStack"<<endl; return false; } stack->next = p->next; *e = p->data; free(p); p = NULL; return true; } void DestroyStack(LinkStack stack)//销毁链表 { Node *p = stack; Node *q = NULL; while (!p) { q = p; p = p->next; free(q); q = NULL; } } bool Match(ElemType e,ElemType ch)//判断括号 { if ( ('(' == e) && (')'== ch) ) return true; else if ( ('{' == e) && ('}' == ch) ) return true; else if ( ('[' == e) && (']' == ch) ) return true; else return false; }
#include "match.h" int main(void) { char *p; ElemType e; ElemType ch[MAXLEN]; LinkStack s; InitStack(&s); cout << "Please input the expression with bracket('()','{}','[]')" << endl; gets_s(ch); p = ch; while (*p) { switch (*p) { case '(': case '[': case '{': PushStack(s,*p++); break; case ')': case ']': case '}': if ( StackEmpty(s) ) { cout << "miss left bracket!" << endl; return 0; } else { GetTop(s,&e); /*栈不为空 读取的是右括号 则取出栈顶括号*/ if (Match(e,*p)) /*判断栈顶括号是否为右括号*/ { PopStack(s,&e);/*若栈顶括号和右括号匹配,则栈顶括号出栈*/ } else /*不匹配*/ { cout << "not match" << endl; return 0; } } default: p++; } } if (StackEmpty(s)) cout << "bracket match!" << endl; else cout << "not match,miss right bracket" << endl; return 0; }
原文链接:https://www.f2er.com/datastructure/382675.html