数据结构----顺序栈实现逆波兰表达式(后缀表达式)求解

来源:互联网 发布:应急数据采集更新制度 编辑:程序博客网 时间:2024/06/04 19:07
<span style="font-family: Arial, Helvetica, sans-serif;">//栈的应用,用栈来求解逆波兰表达式</span>
#include "stdafx.h"#include <stdio.h>#include <stdlib.h>#include <string.h>#include <ctype.h>#include <math.h>typedef  double ElemType;//栈存储的元素类型#define STACK_INCREMENT_LENGTH 10//栈的增长长度typedef struct node{ElemType *top;//栈顶ElemType *bottom;//栈底int max_length;//栈的最大容量}SqStack;int initStack(SqStack &s, int n)//初始化一个栈,栈的容量为n{s.bottom = (ElemType *)malloc(n*sizeof(SqStack));//初始化内存空间if(!s.bottom)//内存分配失败return 0;s.top = s.bottom;s.max_length = n;return 1;}int push(SqStack &s, ElemType e){if(s.top - s.bottom >= s.max_length)//栈满{s.bottom = (ElemType *)realloc(s.bottom, (s.max_length + STACK_INCREMENT_LENGTH)*sizeof(ElemType));if(!s.bottom)//分配内存失败return 0;s.top = s.bottom + s.max_length;s.max_length = s.max_length + STACK_INCREMENT_LENGTH;}*s.top = e;s.top++;return 1;}int pop(SqStack &s, ElemType &e)//出栈的元素保存在变量e中{if(s.bottom == s.top)//栈空return 0;e = *(--s.top);return 1;}void clearStack(SqStack &s)//清空栈{s.top = s.bottom;}void destroyStack(SqStack &s)//摧毁栈{int i, len;len = s.max_length;for(i=0; i < len; i++){free(s.bottom);s.bottom++;}s.bottom = s.top = NULL;s.max_length = 0;}int getN(SqStack &s){return s.top-s.bottom;}int main(){SqStack s;initStack(s, 100);char c;double d, e;int i = 0;char str[20];printf("请输入正确的逆波兰表达式,数字与符号之间用空格隔开,以'#'结束:\n");scanf("%c", &c);while(c!='#'){while(isdigit(c) || c == '.')//将字符如:3.1415926转换为浮点数{str[i++] = c;str[i] = '\0';if(i >= 10){printf("\n单个数据精度过大\n");return -1;}scanf("%c", &c);if(c == ' ')//单个数据输入结束{d = atof(str);push(s, d);i = 0;break;}}switch(c)//根据运算符计算{case '-':pop(s, d);pop(s, e);push(s, e-d);break;case '+':pop(s, d);pop(s, e);push(s, e+d);break;case '*':pop(s, d);pop(s, e);push(s, e*d);break;case '/':pop(s, d);pop(s, e);if(d == 0){printf("\n表达式错误,除数为0\n");return -1;}push(s, e/d);break;}scanf("%c", &c);}pop(s, e);printf("结果为:%lf\n", e);return 0;}

0 0