今天脑袋迷迷糊糊的,愣是不知道为什么出问题。。。
这是一个中缀表达式转后缀表达式的程序,但不知道为什么,每次输入时最先入栈的符号都会输出两次,求各位大神指导!
#include<iostream>
#include<string.h>
#include<malloc.h>
#define maxsize 300
using namespace std;
typedef struct{
char data[maxsize];
int top;//栈顶指针
}stack;
void init(stack *&s)//初始化顺序栈/建立新的空栈
{
s=(stack*)malloc(sizeof(stack));
s->top=-1;//将栈顶指针指向-1
}
bool push(stack *&s,char e)//将e元素入栈
{
if(s->top==maxsize-1)//若栈已满,无法入栈
{return false;}
s->top++;//栈顶补增1,若栈顶指针为-1相当于启动空栈
s->data[s->top]=e;
return true;
}
bool pop(stack *&s)//出栈顶元素
{
if(s->top==-1)//栈为空,无法出栈
{return false;}
cout<<s->data[s->top];
s->top--;
return true;
}
void sort(stack *&L,char b[])
{
int n,i,s;
char e;
n=strlen(b);
for(i=0;i<n;i++)
{
if(b[i]=='(')
{
push(L,b[i]);
}
else if(b[i]=='*'||b[i]=='/')
{
if(L->top==-1)
{push(L,b[i]);}
else{
while(L->data[L->top]=='*'||L->data[L->top]=='/')
{
pop(L);
}}
push(L,b[i]);
}
else if(b[i]=='+'||b[i]=='-')
{
if(L->top==-1)
{push(L,b[i]);}
else{
while(L->data[L->top]=='+'||L->data[L->top]=='-'||L->data[L->top]=='*'||L->data[L->top]=='/')
{
pop(L);
}}
push(L,b[i]);
}
else if(b[i]==')')
{
if(L->top==-1)
{push(L,b[i]);}
else{
while(L->data[L->top]!='(')
{
pop(L);
if(L->data[L->top]=='(')
{
L->top--;
break;
}
}
}
}
else
{
cout<<b[i];
}
}
while(L->top!=-1)
{
pop(L);
}
}
int main()
{
char a[300];
cin>>a;
stack *L;
init(L);
sort(L,a);
return 0;
}
https://blog.csdn.net/jingjingliang1995/article/details/80619649