<span style="font-size:18px;">#include <iostream>
#include "stdlib.h"
#include "string.h"
using namespace std;
char a[10000];
typedef struct node{ //声明节点
char data;
node* next;
}node,*stack;
stack init(char c){ //初始化栈
node* l;
l=(node *)malloc(sizeof(node));
if(l==NULL){
return NULL;
}
l->next=NULL;
node* p;
p=(node *)malloc(sizeof(node));
p->data=c;
p->next=NULL;
l->next=p;
return l;
}
stack pop(stack &l){ //出栈,获取元素用于后面(右)字符比较
node* p;
p=l->next;
node* q;
q=(node *)malloc(sizeof(node));
q->data=p->data;
l->next=l->next->next;
return q;
}
void push(stack &l,char c){ //进栈,(左)字符
node* p;
p=l;
node* q;
q=(node *)malloc(sizeof(node));
q->data=c;
q->next=p->next;
p->next=q;
}
int main(int argc, char* argv[])
{
stack l;
stack r;
int k,sum=0;
cin>>k;
if(k>0&&k<=100){
do{
a[10000];
cin>>a;
int t=strlen(a);
if(t%2==1){
cout<<"No"<<endl;
}else{
if(a[0]==']'||a[0]==')'){
cout<<"No"<<endl;
}else{
int i=0;
l=init(a[i]);
for(i=1;i<t;i++){
if(a[i]=='['||a[i]=='('){
push(l,a[i]);
}else{
r=pop(l);
if(a[i]==')'){
if(r->data!='('){
cout<<"No"<<endl;
break;
}
}
if(a[i]==']'){
if(r->data!='['){
cout<<"No"<<endl;
break;
}
}
}
}
if(i==t){
cout<<"Yes"<<endl;
}
}
}
sum++;
}while(sum<k);
}
return 0;
}</span>
用栈解决括号配对问题
最新推荐文章于 2022-05-11 22:48:32 发布