逆波兰计数器又叫后缀表达式
先上代码
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
// 1 先实现一个栈结构
#define STACK_INIT_SIZE 20 // 初始大小
#define STACK_INCREMENT 10 // 增长大小
#define MAX_BUFFER 10 // 最大缓冲区
typedef double ElemType;
typedef struct
{
ElemType *bottom;// 栈底指针
ElemType *top;// 栈顶指针
int stackSize;// 栈的大小
} sqStack;
// 2 实现初始化 压入 弹出方法
void InitStack(sqStack *s) {
s->bottom = (ElemType *)malloc(sizeof(ElemType) * STACK_INIT_SIZE);
if (!s->bottom)
{
exit(0);
}
s->top = s->bottom;
s->stackSize = STACK_INIT_SIZE;
}
void Pop(sqStack *s, ElemType *value) {
if (s->top == s->bottom)
{
return;
}
s->top--;
*value = *(s->top);
}
void Push(sqStack *s, ElemType value) {
if (s->top - s->bottom >= s->stackSize) // 说明已经满了 要增加空间才行
{
s->bottom = (ElemType *)realloc(s->bottom, (s->stackSize * STACK_INCREMENT) * sizeof(ElemType));
if (!s->bottom)
{
exit(0);
}
}
*(s->top) = value;
s->top++;
}
int StackLen(sqStack s) {
return s.top - s.bottom;
}
int main()
{
sqStack s;
char c;
double d,e;
char str[MAX_BUFFER];
int i = 0;
InitStack(&s);
printf("请按照逆波兰表达式输入待计算数据,数据与运算符之间用空格隔开,以#结束\n");
scanf("%c", &c);
while(c != '#') {
while(isdigit(c) || c == '.') {
str[i++] = c;
str[i] = '\0';
if (i >= 10)
{
printf("输入的单个数据过大\n");
return -1;
}
scanf("%c", &c);
if (c == ' ')
{
d = atof(str);
Push(&s, d);
i = 0;
break;
}
}
switch(c) {
case '+':
Pop(&s, &e);
Pop(&s, &d);
Push(&s, e + d);
break;
case '-':
Pop(&s, &e);
Pop(&s, &d);
Push(&s, d - e);
break;
case '*':
Pop(&s, &e);
Pop(&s, &d);
Push(&s, d * e);
break;
case '/':
Pop(&s, &e);
Pop(&s, &d);
if (d != 0)
{
Push(&s, d / e);
} else {
printf("除数为0\n");
return -1;
}
break;
}
scanf("%c", &c);
}
Pop(&s, &d);
printf("最后结果 %f\n", d);
return 0;
}
程序执行结果
第一个计算的是(1 - 2) + (4 * 5)
第二个计算的是5 + (6 + 7)* 8 + 9 / 4