|
发表于 2018-4-24 20:31:55
From FishC Mobile
|
显示全部楼层
|阅读模式
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 幽梦三影 于 2018-4-24 22:20 编辑
//逆波兰表达式
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<ctype.h>
#define stack_int_size 20
#define expand 10
typedef double elemtype;
typedef struct
{
elemtype *top;
elemtype *base;
int stacksize;
}
stack;
//创建一个栈
void creatstack(stack* s)
{
s->base=(elemtype*)malloc(stack_int_size*sizeof(elemtype));
if(!(s->base))
exit(0);
s->top=s->base;
s->stacksize=stack_int_size;
}
//插入操作
void push(stack* s,elemtype e)
{
if(s->top-s->base>=s->stacksize)
s->base=(elemtype*)realloc(s->base,(s->stacksize+expand)*sizeof(elemtype));
if(!(s->base))
exit(0);
s->top=s->base+s->stacksize;
s->stacksize=s->stacksize+expand;
*(s->top)=e;
s->top++;
}
//删除操作
void pop(stack* s,elemtype e)
{
if(s->top==s->base)
printf("空栈!");
return;
--(s->top);
e=*(s->top)
}
int main()
{
stack s;
int i=0;
char c,m[stack_int_size];
//m为缓冲区,存放输入的字符
double d,e,f,l;//用于暂时存放输入的数据,并进行相互运算
creatstack(&s);
printf("请输入逆波兰算数式:\n");
scanf("%c",&c);
while(c!='#') //用#作为结束
{
while(isdigit(c)||c=='.')
{
m[i++]=c;
m[i]='\0';
//这是什么用啊?
scanf("%c",&c);
if(c==' ') //用空格终止一次循环,在外层while循环结尾再输入c再次进入循环
{
f=atof(m);//把m缓冲区中的小数字符转换成double型
push(&s,f);
i=0;
break;
}
}
switch(c)
{
case '+':
pop(&s,d);
pop(&s,e);
push(&s,d+e);
break;
case '-':
pop(&s,d);
pop(&s,e);
push(&s,e-d);
break;
case '*':
pop(&s,d);
pop(&s,e);
push(&s,d*e);
break;
case '/':
pop(&s,d);
pop(&s,e);
if(e==0) //分母不为0
{
printf("error\n");
return -1;
} else
push(&s,e/d);
break;
}
scanf("%c",&c);
}
pop(&s,l);
printf("\n%lf\n",l);
return 0;
} |
|