后缀表达式求值的算法及代码
case'-':return(operand1-operand2);
}
}
void main() //主函数
{
char exp[100];
int operand1=0; //定义操作数1
int operand2=0; //定义操作数2
int result=0; //定义操作结果
int pos=0;
printf("\t\n请输入后缀表达式:");
operand=pop(operand,&operand2);
operand=push(operand,getvalue(exp[pos],operand1,operand2));//计算结果入栈
}
else
operand=push(operand,exp[pos]-48); //是操作数,压入操作数栈
}
newnode->data=value; //创建结点的内容
newnode->next=stack;
stack=newnode; //新结点成为栈的开始
return stack;
}
link pop(link stack,int *value) //出栈
{
link top; //指向栈顶
if (stack !=NULL)
{
if (stack!=NULL)
return 1;
else
return 0;
}
int isoperator(char op) //判运算符
{
switch (op)
{
case'+':
case'-':
case'*':return 1; //是运算符,返回1
case'/':return 0; //不是运算符,返回0
}
}
int getvalue(int op,int operand1,int operand2) //计算表达式值{switch((char)op)
{
case'*':return(operand1*operand2);
case'/':return(operand1/operand2);
case'+':return(operand1+operand2);
pos++; //移到下一个字符串位置
}
operand=pop(operand,&result); //弹出结果
printf("%d\n",result); //输出
}
link operand=NULL; //操作数栈指针
link push(link stack,int value) //进栈
{
link newnode; //新结点指针
newnode=new stacklist; //分配新结点
if (!newnode)
{
printf("分配失败!");
return NULL;
{
top=stack; //指向栈顶
stack=stack->next; //移动栈顶指针
*value=top->data; //取数据
delete top; //吸收结点
return stack; //返回栈顶指针
}
else
*value=-1;
}
int empty(link stack) //判栈空
#include<stdlib.h>
#include<stdio.h>
struct node //栈结构声明
{
int data; //数据域
struct node *next; //指针域
};
typedef struct node stacklist; //链表类型
typedef stacklist *link; //链表指针类型
gets(exp); //读取表达式
printf("\t\n\n后缀表达式[%s]的计算结果是:",exp);
while (exp[pos] !='\0' && exp[pos] !='\n') //分析表达式字符串
{
if (isoperator(exp[pos])) //是运算符,取两个操作数
{
operand=pop(operand,&operand1);