#include <stdio.h>
#include <cstdlib>
#include <iostream>
#define Maxsize 100
typedef struct SNode{
char data;
struct SNode *next;
}SNode,*StackList;
char str[Maxsize];
/**
* 判断栈空
* @param L
* @return
*/
bool Empty(StackList L){
if(L->next==NULL) return false;
else return true;
}
/**
* 初始化栈
* @param s
* @return
*/
bool InitStack(StackList &s){
s = (SNode*)malloc(sizeof (SNode));
if(s==NULL) return false;
s->next=NULL;
return true;
};
/**
* 在一个节点后进行插入(进栈)
* @param p
* @param e
* @return
*/
bool InsertNextNode(SNode *p,char e){
SNode *q = (SNode*)malloc(sizeof (SNode));
if(q==NULL) return false;
q->next=p->next;
p->next=q;
q->data=e;
return true;
}
/**
* 删除指定节点后的节点
* @param p
* @return
*/
bool DeleteNextNode(SNode *p){
if(p==NULL) return false;
SNode *q=p->next;
p->next=q->next;
free(q);
return true;
}
/**
* 栈顶元素出栈
* @param S
* @return
*/
char PopEle2(StackList &S){
if(Empty(S) == false) return false;
SNode *q=S->next;
S->next=q->next;
return q->data;
}
int main() {
StackList L;
InitStack(L);
int i=0;
float num1,num2,sum;
char buffer[10];//缓冲区,存放操作数
char ch;
std::cout<<"请输入后缀表达式:(用空格隔开,以#为结束标志)"<<std::endl;
scanf("%c",&ch); //接收一个字符
while (ch!='#'){ //判断是否为#
while (ch>'0'&&ch<'9'){
buffer[i]=ch;
i++;
buffer[i]='\0';//字符串结尾
scanf("%c",&ch);
if(ch==' '){
float temp=atof(buffer); //转化数字
InsertNextNode(L,temp); //入栈
i=0; //清空变量
break;
}
}
//遇到操作符就弹出两个栈顶元素进行操作然后入栈
if (ch=='+'||ch=='-'||ch=='*'||ch=='/'){
switch (ch) {
case '+':
num1 = PopEle2(L);
num2 = PopEle2(L);
sum = num1+num2;
InsertNextNode(L,sum);
break;
case '-':
num1 = PopEle2(L);
num2 = PopEle2(L);
sum = num2-num1;
InsertNextNode(L,sum);
break;
case '*':
num1 = PopEle2(L);
num2 = PopEle2(L);
sum = num1*num2;
InsertNextNode(L,sum);
break;
case '/':
num1 = PopEle2(L);
num2 = PopEle2(L);
sum = num2/num1;
InsertNextNode(L,sum);
break;
}
}
scanf("%c",&ch);//开启下一次读取
}
int re = PopEle2(L);
std::cout<<re<<std::endl;
return 0;
}
3.3用栈实现后缀表达式计算
于 2021-07-19 23:33:56 首次发布