数据结构关于栈的编程题成绩:10 / 折扣:0.8  带有变量的中缀表达式是常见的数学表达式.如果规定变量由长度不超过 8 个小写字母组成;end为保留字,表示程序段结束;用?表示输出指定变量

来源:学生作业帮助网 编辑:作业帮 时间:2024/05/01 00:28:25

数据结构关于栈的编程题成绩:10 / 折扣:0.8  带有变量的中缀表达式是常见的数学表达式.如果规定变量由长度不超过 8 个小写字母组成;end为保留字,表示程序段结束;用?表示输出指定变量
数据结构关于栈的编程题
成绩:10 / 折扣:0.8
  带有变量的中缀表达式是常见的数学表达式.如果规定变量由长度不超过 8 个小写字母组成;end为保留字,表示程序段结束;用?表示输出指定变量的值,则可以设计出比较复杂的表达式(即一个可顺序执行语句序列).例如,如果有如下语句段:
abc=10
def=8
c=abc+def
abc=abc+5-c*2
end
则输出为:
c=18
abc=-21
注意:为了简化编程实现,运算符只有+,-,*,/ ,%和^(指数运算),可以处理圆括号(),并假定输入的算术表达式正确.
要求:使用栈结构实现.
输入:表达式序列
输出:全部指定变量的值
表达式中的全部计算结果均为整数.如果在计算过程中出现除数为0的情况,则输出:Divide 0.
特殊情况说明:
在表达式中,如果操作数出现负数(例如-8),则要特别注意.例如:
10加-8表示为:10+-8.
10减-8表示为:10--8.

数据结构关于栈的编程题成绩:10 / 折扣:0.8  带有变量的中缀表达式是常见的数学表达式.如果规定变量由长度不超过 8 个小写字母组成;end为保留字,表示程序段结束;用?表示输出指定变量
#include"stdio.h"
#include"stdlib.h"
#define NULL 0
#define m 5
struct node
{
int elem;
struct node *lchild,*rchild;
};
struct node *T,*p,*q;
struct node* Delete(struct node*t);
void DeleteNode(struct node*t);
void insertnode(struct node*t,int kx);
void postordertraverse(struct node *t);
int searchelm(struct node*t,int k);
int set_key();
void main()
{
int x,i=0,L[m],key,found;
printf("1查找元素\n");
do{
printf("请选择:");
key=set_key();
switch(key)
{
case 1:
T=(struct node*)malloc(sizeof(struct node));
T->lchild=NULL;
T->rchild=NULL;
for(i=0;ielem=L[0];
for(i=1;ilchild))
\x09\x09{
t1=(struct node*)malloc(sizeof(struct node));
t1->elem=kx;
t->lchild=t1;
\x09\x09 t1->lchild=NULL;
\x09\x09 t1->rchild=NULL;
\x09\x09}
\x09\x09
else
\x09 insertnode(t->lchild,kx);
}
else
{
\x09 if(!(t->rchild))
\x09 {
t1=(struct node*)malloc(sizeof(struct node));
t1->elem=kx;
t1->elem=kx;
t->rchild=t1;
t1->lchild=NULL;
\x09\x09 t1->rchild=NULL;
\x09 }
\x09 else
insertnode(t->rchild,kx);
}
}
}
void postordertraverse(struct node *t)
{
if(t!=NULL)
{
postordertraverse(t->lchild);
printf("%d ",(*t).elem);
postordertraverse(t->rchild);
}
}
int searchelm(struct node *t,int k)
{
int flag=0;
p=q=t;
while(q)
\x09{
if(k>q->elem)
\x09 {
\x09 p=q;
\x09 q=q->rchild;
\x09 }
else if(kelem))
\x09\x09 {
\x09 p=q;
\x09 q=q->lchild;
\x09\x09 }
\x09 else
\x09\x09 {
\x09 flag=1;
\x09 break;
\x09\x09 }
\x09
}
\x09return(flag);
}
void DeleteNode(struct node*t)
{
struct node *s;
if(p==q)
\x09{
\x09 s=Delete(T);
\x09 T=s;
\x09}
else
\x09 {
\x09 s=Delete(q);
if(p->rchild==q)
p->rchild=s;
\x09 else
\x09\x09 p->lchild=s;
}
}
struct node* Delete(struct node*t1)
{
struct node*p1,*p2,*t;
t=t1;
if(t->rchild!=NULL)
\x09{
\x09 t=t->rchild;
p2=p1=t;
\x09 while(p1!=NULL)
\x09\x09{
\x09 p2=p1;
p1=p1->lchild;
\x09\x09}
\x09 p2->lchild=t1->lchild;
\x09}
else if(t->lchild!=NULL)
\x09\x09 t=t->lchild;
else
\x09t=NULL;
\x09 return(t);
}
int set_key()
{
int key;
static int flag=0;
for(;;)
{
while(1)
{
scanf("%d",&key);
if(key==1||key==2||key==3)
\x09 break;
else
printf("输入1,2或3;重新输入:");
}
if(key==1)
\x09 flag=1;
if(flag==1)
\x09 break;
else
\x09printf("输入错误;重新输入:");
}
return(key);
}
我写的 很不错哦