文档库 最新最全的文档下载
当前位置:文档库 › 实用数据结构基础(第二版)实验3:后缀表达式求值-1

实用数据结构基础(第二版)实验3:后缀表达式求值-1

实用数据结构基础(第二版)实验3:后缀表达式求值-1.txt让人想念而死,是谋杀的至高境界,就连法医也鉴定不出死因。。。。。。#include
#include
struct node // 栈结构声明
{
int data; // 数据域
struct node *next; // 指针域
};
typedef struct node stacklist; // 链表类型
typedef stacklist *link; // 链表指针类型
link operand=NULL; // 操作数栈指针

link push(link stack,int value) // 进栈
{
link newnode; // 新结点指针
newnode=new stacklist; // 分配新结点
if (!newnode)
{
printf("分配失败!");
return NULL;
}
newnode->data=value; // 创建结点的内容
newnode->next=stack;
stack=newnode; // 新结点成为栈的开始
return stack;
}

link pop(link stack,int *value) // 出栈
{
link top; // 指向栈顶
if (stack !=NULL)
{
top=stack; // 指向栈顶
stack=stack->next; // 移动栈顶指针
*value=top->data; // 取数据
delete top; // 吸收结点
return stack; // 返回栈顶指针
}
else
*value=-1;
}

int empty(link stack) // 判栈空
{
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);
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 请输入后缀表达式:");
gets(exp); // 读取表达式
printf("\t\n\n 后缀表达式[%s]的计算结果是:",exp);
while (exp[pos] !='\0' && exp[pos] !='\n') // 分析表达式字符串
{
if (isoperator(exp[pos])) // 是运算符,取两个操作数
{
operand=pop(operand,&operand1);
operand=pop(operand,&operand2);

operand=push(operand,getvalue(exp[pos],operand1,operand2));// 计算结果入栈
}
else
operand=push(operand,exp[pos]-48); // 是操作数,压入操作数栈
pos++; // 移到下一个字符串位置
}
operand=pop(operand,&result); // 弹出结果
printf("%d\n",result); // 输出
}

相关文档
相关文档 最新文档