栈--括号匹配

来源:互联网 发布:淘宝办学历学信网可查 编辑:程序博客网 时间:2024/05/18 15:06
#include <iostream>using namespace std;class Ele{private:public:char data;Ele* next;//Ele(void);//~Ele(void);void setData(int d){data=d;}void setNext(Ele* p){next=p;}};class Stack{private:public:Ele* first;int length;Stack(){first=NULL;length=0;}//~Stack();void create(int len){for(int i=0;i<len;i++){Ele* p=new Ele();p->data=i;p->next=NULL;push(p);length++;}}void push(Ele* e){if(ifEmpty()){first=e;}else{e->next=first;first=e;}length++;}Ele* pop(){Ele* p=NULL;if(!ifEmpty()){p=first;first=first->next;p->next=NULL;length--;}return p;}bool ifEmpty(){if(length==0)return true;else return false;}};bool check(char c1,char c2){switch(c1){case '(':if(c2==')')return true;break;case '{':if(c2=='}')return true;break;case '[':if(c2==']')return true;break;}return false;}int main(){Stack sta;char c;int mark=0;cin.get(c);while(c!='\n'){//cout<<"c:"<<c<<"mark:"<<mark<<endl;if(c=='{'||c=='('||c=='['){Ele* p=new Ele();p->data=c;p->next=NULL;sta.push(p);//cout<<"push is ok"<<endl;}else if(c=='}'||c==']'||c==')'){//cout<<"length:"<<sta.length<<endl;if(!sta.ifEmpty()){Ele* q=sta.pop();//cout<<"pop:"<<q->data<<"c:"<<endl;if(!check(q->data,c))mark=1;}else mark=2;}cin.get(c);}switch(mark){case 0:cout<<"匹配成功"<<endl;break;case 1:cout<<"匹配错误"<<endl;break;case 2:cout<<"括号缺失"<<endl;break;}system("pause");return 0;}

0 0
原创粉丝点击