顺序栈判断表达式的括号匹配

顺序栈判断表达式的括号匹配

代码如下:

#include <iostream>
using namespace std;
typedef struct sqstack                   //顺序栈定义
{
	char data[10];
	int top;
}Sqstack;

void initstack(struct sqstack &Sqstack) //初始化栈
{
	Sqstack.top=-1;
}

int isempty(struct sqstack &Sqstack)    //判断栈是否空
{
	if(Sqstack.top==-1)
	{
		cout<<" 顺序栈为空 "<<endl;
		return 1;
	}
	else
	{
		cout<<" 顺序栈不为空 "<<endl;
	}
		return 0;
}

int push(struct sqstack &Sqstack,char x)  //插入元素x作为新的栈顶元素
{
	if(Sqstack.top==9)
	{
		cout<<" 错误 "<<endl;
		return 0;
	}
	Sqstack.top=Sqstack.top+1;
	Sqstack.data[Sqstack.top]=x;
	return 1;
}

int gettop(struct sqstack Sqstack,char &e)//得到栈顶元素的值
{
	if(Sqstack.top==-1)
	{
		cout<<" NULL(空表) "<<endl;
		return 0;
	}

	e=Sqstack.data[Sqstack.top];
	return 1;

}
int pop(struct sqstack &Sqstack,char &x)//删除栈顶元素并用x返回它
{
	if(Sqstack.top==-1)
	{
		return 0;
	}
	x=Sqstack.data[Sqstack.top];
	Sqstack.top=Sqstack.top-1;
	return 1;
}

int ifmatch(char exp[],int n)//从字符串中读取元素,
//若为左括号则将它压进栈中再读取到右括号则将出栈(消除一对括号),重复此步骤直到读完字符串。若栈为空说明一对对括号消除即括号匹配,若不为空说明右括号比左括号多即不匹配
//若为右括号则直接说明不匹配
{
  struct sqstack stack;//结构体栈创建实例
  initstack(stack);//初始化
  int i;int x;
  for(i=0;i<n;i++)
  {
    if(exp[i]=='(')
    {push(stack,'(');}
    if(exp[i]==')')
    {
      if(isempty==1)//栈空且只有右括号说明不匹配
      {return 0;}
      else
      {pop(stack,x);}
    }
  }
  if(isempty==1)//栈空说明括号一对对消除则匹配
  {return 1;}
  else
  {return 0;}//栈不空说明站内还剩下未消除的左括号则不匹配
}

int main()
{
  char exp[100];
  int i=0;
  cout<<"请输入表达式:";
  cin>>exp;
  while(exp[i]!='\0')//求输入的字符串长度
  {i++;}
  if(ifmatch(exp,i)==1)
  {cout<<"匹配";}
  else
  {cout<<"不匹配";}
  return 0;
}

运行结果如下:运行结果

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值