我也做了一个~
感觉你那个负数处理怎么会两个数反了~~~
先不说空格问题~输入4 5-应该得到-1但你那个却得到1
~~~
看看我那个效果如何~
就是感觉负数的符号和减号通用这个比较麻烦~
程序代码:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<ctype.h>
#define LEN_STACK sizeof(Stack)
#define LEN_LINKSTACK sizeof(LinkStack)
#define MAX_SIZE 32 //输入缓冲数据储存容量大小
typedef double ElemType;
typedef struct Stack
{
ElemType data;
struct Stack* next; //栈底指针
}Stack,*PStack;
typedef struct LinkStack //栈的链接指针
{
PStack base;
PStack top;
}LinkStack,*PLinkStack;
void Creat_Stack(PLinkStack* s); //创建一个栈
void Push_Stack(PLinkStack s,ElemType data); //进栈
void Pop_Stack(PLinkStack s); //出栈
void Del_Stack(PLinkStack s); //销毁栈
char Get_Single(PLinkStack s); //数据转化并获取运算符号
ElemType Count(PLinkStack s,char c); //计算数据
int IsEmpty_Stack(PLinkStack s); //判断栈空
int main()
{
PLinkStack s=NULL;
ElemType result=0;
char c=0;
Creat_Stack(&s);
puts("请输入后序表达式:每个数字及运算符号之间用空格隔开:");
while ((c=Get_Single(s))!='\n')
Push_Stack(s,Count(s,c));
result=s->top->data;
Pop_Stack(s);
// if (!IsEmpty_Stack(s))
// puts("输入数据出错!");
// else
printf("%.2f\n",result);
Del_Stack(s);
free(s);
s=NULL;
return 0;
}
void Creat_Stack(PLinkStack* s)
{
*s=(PLinkStack)malloc(LEN_LINKSTACK);
if (*s==NULL)
{
puts("分配空间出错!");
exit(0);
}
memset(*s,0,LEN_LINKSTACK);
(*s)->base=(*s)->top=(PStack)malloc(LEN_STACK);
if ((*s)->base==NULL)
{
puts("分配空间出错!");
exit(0);
}
memset((*s)->base,0,LEN_STACK);
}
void Push_Stack(PLinkStack s,ElemType data) //进栈
{
PStack p=(PStack)malloc(LEN_STACK);
if (p==NULL)
{
puts("分配空间出错!");
exit(0);
}
p->data=data;
p->next=s->top;
s->top=p;
}
void Pop_Stack(PLinkStack s) //出栈
{
PStack p=s->top;
if (IsEmpty_Stack(s))
return ;
s->top=s->top->next;
free(p);
}
void Del_Stack(PLinkStack s) //销毁栈
{
while (!IsEmpty_Stack(s))
Pop_Stack(s);
}
int IsEmpty_Stack(PLinkStack s) //判断栈空
{
return s->base==s->top;
}
char Get_Single(PLinkStack s)
{
char c=0;
while (1) //判断是否为负数
{
char buff[MAX_SIZE]={0};
char* p=buff;
while (isdigit(c=getchar())||c=='.'||(c=='-'&&p==buff))
*p++=c;
if (buff[0]=='-'&&!isdigit(buff[1]))
Push_Stack(s,Count(s,'-'));
if (c!=' ')
break;
if (isdigit(buff[0])||(buff[0]=='-'&&isdigit(buff[1])))
Push_Stack(s,atof(buff));
}
return c;
}
ElemType Count(PLinkStack s,char c) //计算数据
{
ElemType a=0;
ElemType b=0;
a=s->top->data;
Pop_Stack(s);
b=s->top->data;
Pop_Stack(s);
switch (c)
{
case '+':return b+a;
case '-':return b-a;
case '*':return b*a;
case '/':
if (b==0)
{
puts("除数不能为0");
exit(0);
}
return b/a;
default:
puts("输入数据出错!");
exit(0);
}
return 0;
}
[此贴子已经被作者于2017-4-8 15:38编辑过]