版权声明:转载请注明出处!不注明也无所谓,嘿嘿。 https://blog.csdn.net/qq_15020543/article/details/82927071
很简单,掌握栈的基础知识即可。
#include <iostream>
#include <string.h>
using namespace std;
struct Node {
int data;
Node *next;
};
class LinkStack {
private :
Node *top;
public :
LinkStack() {
top=NULL;
}
~LinkStack();
void Push(int e);
int Pop();
int GetTop();
void Match(char toBeMatch[],int length);
bool TestEmpty();
};
LinkStack:: ~LinkStack() {
while(top) {
Node *p=new Node;
p=top->next;
delete top;
top=p;
}
}
int LinkStack::Pop() {
if(!top) {
cout<<"溢出"<<endl;
return -1;
}
Node *p=new Node;
p=top;
top=top->next;
delete p;
return 1;
}
void LinkStack::Push(int e) {
Node *s=new Node;
if(!s) {
cout<<"内存分配失败";
return ;
}
s->data=e;
s->next=top;
top=s;
}
int LinkStack::GetTop() {
if(top) {
return top->data;
}
}
void LinkStack::Match(char toBeMatch[],int length) {
int count=0,state=1;
while(count<length) {
char temp=toBeMatch[count];
switch (temp) {
case '(':
Push(1);
count++;
break;
case '[':
Push(2);
count++;
break;
case ')':
if(GetTop()==1) {
Pop();
} else {
state=0;
}
count++;
break;
case ']':
if(GetTop()==2) {
Pop();
} else {
state=0;
}
count++;
break;
default : {
count++;
break;
}
}
}
if(state==0||TestEmpty()==false) {
cout<<"未匹配成功"<<endl;
} else if(state==1&&TestEmpty()==true) {
cout<<"匹配成功"<<endl;
}
}
bool LinkStack:: TestEmpty() {
if(top) {
return false;
} else {
return true;
}
}
int main() {
char toBeMatch[100];
int length;
while(true) {
cout<<"请输入想要匹配的括号(注意只支持英文格式):"<<endl;
cin>>toBeMatch;
cout<<"想要匹配前几个括号?:"<<endl;
cin>>length;
LinkStack linkStack;
linkStack.Match(toBeMatch,length);
memset(toBeMatch, 0, sizeof(toBeMatch));
}
return 0;
}