用栈解决括号配对问题

<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>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值