一个有问题的中缀表达式转后缀表达式代码
记录一下,之后慢慢改
main.c
#include <ctype.h>
#include "LinStack.h"
void fun(LSnode *myhead,Datatype x1,Datatype x2)
{
Stackpop(myhead,&x1);
printf("%c",x1);
StackTop(myhead,&x1);
if(x1<x2)
{
StackPush(myhead,x2);
}
else
{
fun(myhead,x1,x2);
}
}
void main()
{
int i;
char c,str[20],a,x1,x2;
LSnode *myhead;
c='#';
StackInititate(&myhead);
if(StackPush(myhead,c))
{
printf("入栈成功!\n");
}
StackTop(myhead,&a);
printf("请输入中缀表达式:\n");
scanf("%s",str);
for(i=0;str[i]!='#';i++)
{
if(isdigit(str[i]))
printf("%c",str[i]);
else
{
StackTop(myhead,&x1);
x2=str[i];
if(x1=='+'||x1=='-')
{
if(x2=='*'||x2=='/'||x2=='(')
{
StackPush(myhead,x2);
}
else
{
fun(myhead,x1,x2);
}
}
else if(x1=='*'||x1=='/')
{
if(x2=='(')
{
StackPush(myhead,x2);
}
else
{
fun(myhead,x1,x2);
}
}
else if(x1=='('||x2!='#')
{
if(x2==')')
{
StackPush(myhead,x1);
}
else
{
StackPush(myhead,x2);
}
}
else if(x1=='#'||x2!=')')
{
if(x1=='#')
{
break;
}
else
{
StackPush(myhead,x2);
}
}
else if(x1==')'&&x2!='(')
{
fun(myhead,x1,x2);
}
}
}
while(StackNotEmpty(myhead))
{
Stackpop(myhead,&x1);
if(x1!='#'&&x1!='('&&x1!=')')
printf("%c",x1);
}
}
LinStack.h
#include <stdio.h>
#include <malloc.h>
#include <ctype.h>
typedef char Datatype;
typedef struct snode
{
Datatype data;
struct snode *next;
}LSnode;
void StackInititate(LSnode **head)
{
*head=(LSnode *)malloc(sizeof(LSnode));
(*head)->next=NULL;
printf("链式堆栈初始化成功!\n");
}
int StackNotEmpty(LSnode *head)
{
if(head->next==NULL)
return 0;
else
return 1;
}
int StackPush(LSnode *head,Datatype x)
{
LSnode *p;
p=(LSnode *)malloc(sizeof(LSnode));
p->next=head->next;
p->data=x;
head->next=p;
return 1;
}
int Stackpop(LSnode *head,Datatype *x)
{
LSnode *p;
p=head->next;
if(p==NULL)
{
printf("堆栈元素已为空!\n");
return 0;
}
*x=p->data;
head->next=p->next;
free(p);
return 1;
}
int StackTop(LSnode *head,Datatype *x)
{
LSnode *p;
p=head->next;
if(p==NULL)
{
printf("堆栈元素已为空!\n");
return 0;
}
*x=p->data;
return 1;
}
//问题是:当字符串到最后一个‘#’是,栈顶元素应该可以继续和‘#’比较