数据结构-逆波兰计算器

  • 2020-10-08
  • 0
  • 0

逆波兰计算器的实现

/***链栈的实现***/
#include<stdlib.h>
#include<stdio.h>
#include<iostream>
#include<fstream>
using namespace std;

#define OK 1
#define ERROR -1
#define OVERFLOW -2
#define MAXBUFFER 10
#define STACK_INIT_SIZE 20
#define STACINCREMENT 10


typedef int Status;
typedef double SElemType;

typedef struct StackNode {
	SElemType data;//存放栈数据
	struct StackNode *next;
} StackNode, *LinkStack;

//算法3.5 链栈的初始化
Status InitStack(LinkStack &s) { // 构造一个空栈 S,栈顶指针置空
	s = NULL;
	return OK;
}
//算法3.6 链栈的入栈
Status Push(LinkStack &s, SElemType e) {//在栈顶插入元素e
	LinkStack p;
	p = new StackNode; //生成新结点
	p->data = e; //将新结点数据域置为e
	p->next = s; //将新结点插入栈顶
	s = p; //修改栈顶指针为p
	return OK;
}

//算法3.7 链栈的出栈
Status Pop(LinkStack &s, SElemType &e) {//删除S的栈顶元素,用e返回其值
	LinkStack p;
	if (s == NULL)
		return ERROR; //栈空
	e = s->data; //将栈顶元素赋给e
	p = s; //用p临时保存栈顶元素空间,以备释放
	s = s->next; //修改栈顶指针
	delete p; //释放原栈顶元素的空间
	return OK;
}
int main()
{
	LinkStack s;
	char c;
	double d,e;
	char str[MAXBUFFER];
	int i = 0;
	InitStack(s);
	cout << "请按逆波兰表达式输入计算式,数据与运算符之间用空格隔开,以#为结束标志\n";
	cin >> c;
	cout << c;

	while(c != '#')
	{

		while(isdigit(c) || c=='.')
		{
			str[i++] = c;
			str[i] = '\0';
			if(i >= 10)
			{
				cout <<"出错:输入单个数据过大!\n";
				return -1;

			}
			cin >> c;
			if(c == ' ')
			{
				d = atof(str);
				Push(s,d);
				i = 0;
				break;
			}
		}
		switch(c)
		{
			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);
				Push(s,d*e);
				break;

			case '/':	
				Pop(s,e);
				Pop(s,d);
				if(e != 0)
				{
					Push(s,d/e);
				}
				else
				{
					cout <<"\n出错,除数为0";
					return -1;
				}
				break;
		}

	cin >> c;
	}
	Pop(s, d);
	cout << "\n最终的计算结果为" << d << "\n";
	return 0;
}

评论

还没有任何评论,你来说两句吧