#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;
}
棧--括號匹配
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.