【資料結構】棧的應用 括弧匹配,資料結構括弧匹配
括弧配對問題:
假設一個運算式中包含三種類型的括弧:(),{ },【】,嵌套順序任意
{ 【()()】 }
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 100typedef 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;elsereturn 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;elsereturn 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;elsecout << "not match,miss right bracket" << endl;return 0;}