数据结构学习:链栈实现括号匹配

数据结构学习:链栈实现括号匹配
使用链栈来判断输入的括号是否左右匹配
//联系,使用栈结构来判断输入的括号是否符合规则
#include
using namespace std;

typedef struct LinkNode
{
char data;
struct LinkNode *next;
}LinkNode; //链栈结点定义

typedef struct
{
LinkNode *top;
}LinkStack;//定义链栈头指针

//初始化链栈
void InitStack(LinkStack &S)
{
S.top = (LinkNode *)malloc(sizeof(LinkNode));
S.top->next = NULL;
}
//链栈指针由栈顶指向栈底

//新元素入栈
bool Push(LinkStack &S,char x)
{
LinkNode *q = (LinkNode *)malloc(sizeof(LinkNode));
q->data = x;
q->next = S.top->next;//链栈插入新元素
S.top = q; //栈顶指针指向新节点
return true;
}

//元素出栈
bool Pop(LinkStack &S,char &x)//出栈对元素采用&操作
{
if(S.top == NULL)
return false; //栈空
LinkNode *q = (LinkNode *)malloc(sizeof(LinkNode));
q = S.top->next;
x = q->data; //元素出栈
S.top->next = q->next; //栈顶指针后移
free(q);
return true;
}

bool EmptyStack(LinkStack S)
{
if(S.top->next == NULL)
return true;
else
return false;
}
bool bracketChack(char str[],int length)//判断括号是否符合标准
{
LinkStack S;
InitStack(S);
for(int i = 0;i<length;i++)
{
if(str[i] == ‘(’ || str[i] == ‘[’ || str[i] == ‘{’)
{
Push(S,str[i]);
}
else
{
if(EmptyStack(S))
return false;
char topElem;
pop(S,topElem);
if(str[i] == ‘(’ && topElem !=’)’)
return false;
if(str[i] == ‘[’ && topElem !=’]’)
return false;
if(str[i] == ‘{’ && topElem !=’}’)
return false;
}
}
return EmptyStack(S);
}
int main()
{
char str[100];
int len = 0;
char ch;
for(int i = 0;i<100;i++)
{
cin>>str[i] ;
ch = getchar();
if(ch == ‘\n’)//回车结束
break;
len++;
}
if(bracketChack(str))
cout<<“括号符合标准”<<endl;
else
cout<<“不符合标准”<<endl;
return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小二康

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值