#include <stdio.h>
#include <cstdlib>
#include <iostream>
#include <bits/stdc++.h>//万能库
#define Maxsize 100
typedef struct SNode{
char data;
struct SNode *next;
}SNode,*StackList;
char str[Maxsize];
/**
* 判断栈空
* @param L
* @return
*/
bool Empty(StackList L){
if(L->next==NULL) return false;
else return true;
}
/**
* 初始化栈
* @param s
* @return
*/
bool InitStack(StackList &s){
s = (SNode*)malloc(sizeof (SNode));
if(s==NULL) return false;
s->next=NULL;
return true;
}
/**
* 在一个节点后进行插入(进栈)
* @param p
* @param e
* @return
*/
bool InsertNextNode(SNode *p,char e){
SNode *q = (SNode*)malloc(sizeof (SNode));
if(q==NULL) return false;
q->next=p->next;
p->next=q;
q->data=e;
return true;
}
/**
* 删除指定节点后的节点
* @param p
* @return
*/
bool DeleteNextNode(SNode *p){
if(p->next==NULL) return false;
SNode *q=p->next;
p->next=q->next;
free(q);
return true;
}
/**
* 栈顶元素出栈
* @param S
* @param x
* @return
*/
bool PopEle(StackList &S,char &x){
if(Empty(S) == false) return false;
SNode *q=S->next;
S->next=q->next;
x = q->data;
free(q);
return true;
}
/**
* 栈顶元素出栈
* @param S
* @return
*/
char PopEle2(StackList &S){
if(Empty(S) == false) return false;
SNode *q=S->next;
S->next=q->next;
return q->data;
}
/**
* 获取指定位次的节点
* @param L
* @param index
* @return
*/
int getItem(StackList L,int index){
SNode *p=L->next;
int j=0;
if (L == NULL) return -1;
while (p->next!=NULL&&j<index-1){
p=p->next;
j++;
}
return p->data;
}
/**
* 括号匹配判断
* @param L
* @param str
* @return
*/
bool judge(StackList L,char str[]){
// /**
// * 方法一
// */
// char x;
// for(int i=0;i<Maxsize&&str[i]!=0;i++){
//
// if(str[i]=='('||str[i]=='['||str[i]=='{')//遇到左括号入栈
// {
// InsertNextNode(L,str[i]);
// continue;
// }
//
// if((str[i]==')'||str[i]==']'||str[i]=='}')&& Empty(L)!= false){//遇到右括号,并且栈不为空则弹出栈顶元素,否则右括号落单
// PopEle(L,x);
// if ((str[i]==')'&&x=='(')||(str[i]==']'&&x=='[')||(str[i]=='}'&&x=='{'))//左右括号进行匹配
// continue;
// else return false;
// } else return false;
// }
// if(Empty(L) != false) return false;//栈不为空说明左括号落单
// return true;
/**
* 方法二
*/
for (int i = 0; i < Maxsize&&str[i]!=0; i++) {//遍历字符串
if(str[i] == '(') InsertNextNode(L,')');//遇到左括号,添加对应的右括号进栈
else if(str[i] == '[') InsertNextNode(L,']');
else if(str[i] == '{') InsertNextNode(L,'}');
else if(Empty(L) == false||str[i]!= PopEle2(L)) return false;//遇到右括号,将栈顶元素弹出与输入的括号进行比较
}
if (Empty(L) == false) return true;//字符串遍历完后,栈为空则成功
else return false;
}
int main() {
StackList L;
char x;
InitStack(L);
std::cin >> str;
if(judge(L,str) == true){
// printf_s("成功");
std::cout<<"success"<<std::endl;
} else
// printf_s("失败");
std::cout<<"fail"<<std::endl;
return 0;
}
3.3用链栈实现括号匹配
于 2021-07-19 11:23:06 首次发布