#include<bits/stdc++.h>
using namespace std;
typedef struct SNode{
char data;
struct SNode *next;
}SNode,*LinkStack;
void InitStack(LinkStack &S){
S=NULL;
}
void Push(LinkStack &S,char ch){
LinkStack p = new SNode;
p->data=ch;
p->next=S;
S=p;
}
int Pop(LinkStack &S){
if(S==NULL) return 0;
else{
LinkStack p;
p=S;
S=S->next;
delete p;
return 1;
}
}
int main(){
LinkStack S;
InitStack(S);
char ch;
int flag=1;
cin>>ch;
while(ch!='#'&&flag){
switch(ch){
case '[':
case '(':
Push(S,ch);
break;
case ')':
if(S!=NULL&&S->data=='('){
Pop(S);
}
else flag=0;
break;
case ']':
if(S!=NULL&&S->data=='['){
Pop(S);
}
else flag=0;
break;
}
cin>>ch;
}
if(S==NULL&&flag) {
cout<<"匹配成功";
}
else{
cout<<"匹配失败";
}
}
数据结构:链栈——括号的匹配
最新推荐文章于 2025-05-01 13:25:47 发布