# 逆波兰计数器 栈的实现

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define INITSIZE 20
#define INCREASE 5
typedef struct Stack {
char*top;
char*base;
int stackSize;
}Stack;
void InitStack(Stack*s) {
s->base = (char*)malloc(sizeof(char));//相当于为首地址申请空间
s->top = s->base;
s->stackSize = INITSIZE;
}
void Push(Stack*s, char c) {
if (s->top- s->base>=s->stackSize) {
s->base = (char*)realloc(s->base, (s->stackSize + INCREASE) * sizeof(char));
//为s->base赋一个新的数值空间，并把s->base移过去
s->top = s->base + s->stackSize;//把s->top
s->stackSize = s->stackSize + INCREASE;
}
*(s->top++) = c;
}
void Pop(Stack*s, char*e) {
if (s->top == s->base)
return;
*e = *(--s->top);
}
int getLen(Stack*s) {
return s->top - s->base;
}
void ClearStack(Stack*s) {
s->top = s->base;
}

//实现逆波兰计数器（后缀计数器）
char b[100] = { 0 };
typedef struct stack2 {
double base[20];
int top;
}Stack2;
int NiBoLan(Stack*s, char*a) {
int i =0, j = 0;
char e;
while (a[i]) {
if (a[i] >= '0'&&a[i] <= '9')
b[j++] = a[i];
else if (a[i] == ')') {
Pop(s, &e);//s已经是个指针了，不能再引用了
while (e != '(') {
b[j++] = ' ';//把逆波兰实现的数据存到数组b上，数字和符号之间以空格相隔
b[j++] = e;
Pop(s, &e);
}
}
else if (a[i] == '+' || a[i] == '-') {
b[j++] = ' ';
if (s->top == s->base || *(s->top - 1) == '(')
Push(s, a[i]);
else{//注意else if的区别
while (getLen(s) && *(s->top - 1) != '(') {
Pop(s, &e);
b[j++] = e;
b[j++] = ' ';
}
Push(s, a[i]);
}
}
else if (a[i] == '*' || a[i] == '/' || a[i] == '(') {
if(a[i]!='(')
b[j++] = ' ';
Push(s, a[i]);
}
else return 0;
i++;
}
while (s->top!=s->base) {
Pop(s, &e);
b[j++] = ' ';
b[j++] = e;
}
return 1;
}
double result(Stack2 s) {
int sum = 0, i = 0,j;
char num[10];
double e, d;
while (b[i]) {
j = 0;
if (b[i] >= '0'&&b[i] <= '9') {
while (b[i] != ' '&&b[i] >= '0'&&b[i] <= '9') {
num[j++] = b[i];
num[j] = 0;//要在num中字符的后一位加上'\0'，表示字符串的终止
i++;
}
e = atof(num);
s.base[++s.top] = e;//进行入栈
}
if (s.top > 0) {
switch (b[i])
{
case '+':
s.base[s.top - 1] = s.base[s.top] + s.base[s.top - 1];
s.top--;
break;
case '-':
s.base[s.top - 1] = s.base[s.top - 1] - s.base[s.top];
s.top--;
break;
case '*':
s.base[s.top - 1] = s.base[s.top] * s.base[s.top - 1];
s.top--;
break;
case '/':
s.base[s.top - 1] = s.base[s.top - 1] / s.base[s.top];
if (s.base[s.top] == 0) {
printf("出现浮点错误！\n");
return -1;
}
s.top--;
break;
default:
break;
}
}
i++;
}
return s.base[s.top];
}

int main() {
Stack s;
InitStack(&s);
Stack2 s2 = {
{ 0 },-1
};//对s2赋予初值
char a[100] = { 0 };
printf("请输入一个算式：");
scanf("%s", a);
int IsCorrect = NiBoLan(&s, a);
if (IsCorrect) {
for (int i = 0; b[i]; i++)
printf("%c", b[i]);
printf("\n");
}
else printf("输入的算式有误！\n");
printf("最后结果为：%.2lf\n", result(s2));
return 0;
}

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120