括号匹配

来源:互联网 发布:程序员课程 编辑:程序博客网 时间:2024/05/15 02:51

括号匹配真是个难题啊,容易出错,本人分享一下自己写的链栈的括号匹配的程序给大家,希望大家帮我改正共同进步,感谢!

云盘分享如下: 

http://yunpan.cn/cspRUvnIf8bn5  提取码 f9b4


#include<iostream>using namespace std;struct node{      char data;      node* next;};class stack{public:      node* top;      int size;//栈的即时长度      stack()      {            top=new node;            top->next=NULL;            size=0;      }      ~stack()      {            if(size==0)//如果栈已空,只用删除头结点            {                  delete top;                  return ;            }            while(top->next)            {                  node* temp=top;                  top=top->next;                  delete temp;            }            delete top;      }      void push(const char data);//入栈函数      bool isEmpty();//判断栈是否为空      bool pop();//弹栈      char gettop();//取栈顶元素};char stack::gettop(){      node* t=top->next;      return t->data;}void stack::push(const char data){       node* newnode=new node;//新建结点      newnode->data=data;      newnode->next=top->next;      top->next=newnode;      size++;}bool stack::isEmpty(){      if(size==0)            return true;      else            return false;}bool stack::pop(){      if(isEmpty())      {            return false;      }      node* del=top->next;      top->next=del->next;      del->next=NULL;      delete del;      size--;      return true;}bool match(string str){      stack zhan;      for(unsigned int i=0;i<str.length();i++)      {            if(str[i]=='(')            {                  zhan.push(str[i]);            }else if(str[i]=='[')            {                  zhan.push(str[i]);            }else if(str[i]=='{')            {                  zhan.push(str[i]);            }            else if(str[i]==')')//栈顶若有与之配对的括号则弹栈,若没有则当即可判断不匹配            {                  if(zhan.gettop()=='(')                  {                        zhan.pop();                  }                  else                  {                        return false;                  }            }else if(str[i]==']')            {                  if(zhan.gettop()=='[')                  {                        zhan.pop();                  }                  else                  {                        return false;                  }            }else if(str[i]=='}')            {                  if(zhan.gettop()=='{')                  {                        zhan.pop();                  }                  else                  {                        return false;                  }            }            else                  continue;      } //for 循环结束      if(zhan.isEmpty()) //最后栈若为空,则证明括号匹配,返回1;否则返回0.            return 1;      else            return 0;}//match 全局函数,括号匹配算法


0 0
原创粉丝点击