写的程序,运行总出现异常,不知怎么改?请高手请教了。。。
下面是我写的程序,运行时,总出现问题,不知怎么改?感觉没错啊?
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#define null 0
struct shuju
{
char a;
struct shuju *next;
}*x1,*head1,*current1;
struct caozuo
{
char b;
struct caozuo *next;
}*x2,*head2,*current2;
void push1(int a1)
{
x1=(struct shuju *)malloc(sizeof(struct shuju));
x1->a=a1;
x1->next=null;
x1->next=head1->next;
head1->next=x1;
}
void push2(char b1)
{
x2=(struct caozuo *)malloc(sizeof(struct caozuo));
x2->b=b1;
x2->next=null;
x2->next=head2->next;
head2->next=x2;
}
char pop1()
{
if(head1->next==null)
{
printf("The linked list is empty!\n");
return 0;
}
else
{
current1=head1->next;
head1->next=current1->next;
return(current1->a);
free(current1);
}
}
char pop2()
{
if(head2->next==null)
{
printf("The linked list is empty!\n");
return 0;
}
else
{
current2=head2->next;
head2->next=current2->next;
return(current2->b);
free(current2);
}
}
char gettop1()
{
return(head1->next->a);
}
char gettop2()
{
return(head2->next->b);
}
char operate(char *a,char theta,char *b)
{
char c;
switch(theta)
{
case '+':c=(char)(atoi(a)+atoi(b));break;
case '-':c=(char)(atoi(a)-atoi(b));break;
case '*':c=(char)(atoi(a)*atoi(b));break;
case '/':c=(char)(atoi(a)/atoi(b));break;
}
return c;
}
char precede(char a,char b)
{
if((a=='+'||a=='-')&&(b=='+'||b=='-'||b==')'||b=='#'))return '>';
if((a=='+'||a=='-')&&(b=='*'||b=='/'||b=='('))return '<';
if((a=='*'||a=='/'||a==')')&&(b=='+'||b=='-'||b=='*'||b=='/'||b==')'||b=='#'))return '>';
if((a=='*'||a=='/'||a==')')&&(b=='('))return '<';
if((a=='('||a=='#')&&(b=='+'||b=='-'||b=='*'||b=='/'||b=='('))return '<';
if((a=='('&&b==')')||(a=='#'&&b=='#'))return '=';
}
int qiuzhi()
{
push2('#');
char c;
c=getchar();
while(c!='#'||gettop2()!='#')
{
if(!(c=='+'||c=='-'||c=='*'||c=='/'||c=='('||c==')'||c=='#'))
{
push1(c);
c=getchar();
}
else
{
switch(precede(gettop2(),c))
{
char a,b;
case '<':push2(c);c=getchar();break;
case '=':pop2();c=getchar();break;
case '>':pop2();b=pop1();a=pop1();push1(operate(&a,pop2(),&b));break;
}
}
}
return gettop1();
}
void main()
{
head1=(struct shuju *)malloc(sizeof(struct shuju));
head1->next=null;
head2=(struct caozuo *)malloc(sizeof(struct caozuo));
head2->next=null;
printf("算数表达式的结果为:%c",qiuzhi());
}
[解决办法]
修改以下2行:
case '>':b=pop1();a=pop1();push1(operate(&a,pop2(),&b));break;//case '>':pop2();b=pop1();a=pop1();push1(operate(&a,pop2(),&b));break;
printf("算数表达式的结果为:%d",qiuzhi());//printf("算数表达式的结果为:%c",qiuzhi());
可以执行10以内的加减乘除,例如:
1+2#
算数表达式的结果为:3
若要执行更大范围的运算,需作较多修改。另外,以下语句不能释放内存:
return(current1->a);
free(current1);