数据结构(九) 用顺序栈实现中缀表达式转为后缀表达式

//用栈实现中缀表达式转为后缀表达式 
//采用的存储结构为顺序存储结构 
#include <iostream>
 
using namespace std;
#define MAXSIZE 100 
//栈的结构体
struct Node
{
int *base; 
int *top;
int stackSize;
}; 
//初始化栈的操作
 void initStack(struct Node &S)
 {
  S.base = new int [MAXSIZE];
  if(S.base == NULL)
  {
  cout<<"地址分配失败\n";
  exit(1);
  }
  S.top = S.base;
  S.stackSize = MAXSIZE;
 }
 //入栈操作
void push(struct Node &S,char e)
{
if(S.top-S.base == S.stackSize)
{
cout<<"此栈已经满了\n";
exit(1);
}
*S.top++ = e;
} 
//出栈操作
void pop(struct Node &S,char &e)
{
if(S.top==S.base)
{
cout<<"栈为空\n";
exit(1);
}
e = *--S.top;
} 
//运算符优先级的函数 
char compare(char ch,char ch_1)
{
if(ch=='+'||ch=='-')
{
if(ch_1=='+'||ch_1=='-'||ch_1==')'||ch_1=='#')
{
return '>';
}
else if(ch_1=='*'||ch_1=='/'||ch_1=='(')
{
return '<';
}
} 
if(ch=='*'||ch=='/')
{
if(ch_1=='+'||ch_1=='-'||ch_1=='*'||ch_1=='/'||ch_1==')'||ch_1=='#')
{
return '>';
}
else if(ch_1=='(')
{
return '<';
}
}
if(ch=='(')
{
if(ch_1==')')
{
return '=';
}
else if(ch_1!='#')
{
return '<';
} 
else
{
cout<<"出错了\n";
exit(1);
}
}
if(ch==')')
{
if(ch_1!='(')
{
return '>';
}
else
{
cout<<"出错了\n";
}
}
if(ch=='#')
{
if(ch_1 == '#')
{
return '=';
}
else if(ch_1!=')')
{
return '<';
}
else
{
cout<<"出错了\n";
}
}
} 
//取栈顶元素 
char getTop(struct Node S)
{
char e;
if(S.base==S.top)
{
cout<<"栈为空\n";
exit(1);
}
e = *--S.top;
return e;
}
//实现功能的函数 
void function(struct Node S)
{
char ch;
cout<<"请输入你要转换的中缀表达式(以#号作为结束符)\n";
cin>>ch;
while(ch!='#')
{
if(ch>='1'&&ch<='9'||ch>='A'&&ch<='Z'||ch>='a'&&ch<='z')
{
cout<<ch<<" ";
}
else
{
char e;
e = getTop(S);
if(ch==')')
{
while(getTop(S)!='(')
{
pop(S,e);
cout<<e<<" ";
}
pop(S,e);
} 
else
{


char result = compare(e,ch);
if(result=='<')
{
push(S,ch);
}

else if(result=='>')
{
pop(S,e);
cout<<e<<" ";
push(S,ch);
} 
} 
}
cin>>ch;
}
char e;
if(ch=='#')
{
while(getTop(S)!='#')
{
pop(S,e);
cout<<e<<" ";
}
}
}
 int main()
 {
  struct Node S;
initStack(S);
push(S,'#');
function(S);
  return 0;
 }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值