#include <stdio.h>
#include <stdlib.h>
#define bool char
#define true 1
#define false 0
#define MaxSize 100
typedef int ElemType;
//定义栈的结构
typedef struct SqStack
{
ElemType data[MaxSize];
int top;//指向栈顶
} SqStack;
//栈的初始化
bool InitStack(SqStack* S)
{
S->top = -1;
return true;
}
//栈判空
bool Empty(SqStack S)
{
if(S.top == -1)
return true;
else
return false;
}
//压栈
bool Push(SqStack* S, ElemType e)
{
//判断栈满的情况
if(S->top == MaxSize-1)
return false;
S->data[++S->top] = e;
return true;
}
//出栈
bool Pop(SqStack* S, ElemType* e)
{
if(S->top == -1)
return false;
*e = S->data[S->top--];
return true;
}
//便利测试用
bool Print(SqStack S)
{
int i;
for( i = 0; i < S.top+1; i++)
{
printf("%d ",S.data[i]);
}
return true;
}
int main()
{
//定义和初始化栈
SqStack S1, S2;
InitStack(&S1);
InitStack(&S2);
int answer;
//输入字符串
char str[20];
scanf("%d ",str);
char c = str[0];
int i = 0;
for(i = 0; str[i] != '\0'; i++)
{
c = str[i];
int x, t;
//printf("%d ",c);
if(str[i] <= '9' && str[i] >= '0') //如果是数字,压入栈中
{
t = 0;
while(str[i] <= '9' && str[i] >= '0')
{
x = str[i]-'0';
t = t*10 + x;
i++; printf("%d\n",t);
}
Push(&S1, t);//入栈
}
//如果是空格,跳过
else if(c == ' ')
continue;
//如果是运算符,进行计算操作
else if(c == '+' || c == '-' || c == '*')
{
int m, p;
Pop(&S1, &m);
Pop(&S1, &p);
if(c == '+')
{
answer = p+m;
}
else if(c == '-')
{
answer = p-m;
}
else if(c == '*')
{
answer = p*m;
}
Push(&S1, answer);
}
}
printf("%d", answer);
return 0;
}
这段代码运行是错的,而且没有打印t,如果要支持负数应该怎么改
我这篇文章有,支持负数小数,可以交流下:栈和队列:理解与使用_创意程序员的博客-CSDN博客
第一个scanf中的%d修改为% s,代表输入字符串
1.错误你先打断点调啊...我看上去第一眼的错误就是那个什么空格则跳过..你那判断的是个空字符串吧
2.负数你要先考虑的是逆波兰式里负数怎么表示(例如表示为它的正数形式乘-1),然后按照正常的执行就好