用堆栈实现四则运算(不带括号)、十进制转八进制

来源:互联网 发布:编写软件用什么软件 编辑:程序博客网 时间:2024/06/16 06:25

堆栈的操作(压栈、出栈、判断空栈)用类来实现

四则运算主程序如下:

#include <stdio.h>#include <process.h>#include "Stack.h"bool num_ope(char s)//判断是否数字{switch (s){case'1':case'2':case'3':case'4':case'5':case'6':case'7':case'8':case'9':case'0':return true;default: return false;}}bool priorty(char a, char b)//判断优先级{if (b == '*' || b == '/' || b == '%'){if (a == '+' || a == '-')return true;else if (a == '*' || a == '/' || a == '%')return false;}if (b == '+' || b == '-'){if (a == '*' || a == '/' || a == '%')return false;else if (a == '+' || a == '-')return false;}}int caculate(int a, int b, char c)//计算结果{switch (c){case'+': return a + b;case'-': return a - b;case'*': return a * b;case'/': return b / a;case'%': return b % a;default: break;}}int main(){int i = 0;char s[100];Stack num, ope;//两个栈printf("输入运算式\n");scanf_s("%s", s, 100);while (s[i] != '\0'){if (num_ope(s[i])){int k = s[i] - 48;num.push(k);//进入操作数栈}else{if (ope.isEmpty())//空栈{ope.push(s[i]);//入栈}else{char m = ope.pop();//取出操作符,用来比较if (priorty(m, s[i]))//级别高{ope.push(m);//先将刚才取出来的操作符放进去ope.push(s[i]);//再将现在的操作符放进来}else//级别低{int a = num.pop();//取出操作数栈中的两个数int b = num.pop();int c=caculate(a, b, m);//计算结果num.push(c);//将结果放回操作数栈ope.push(s[i]);//将当前操作符放入栈}}}i++;}if (ope.isEmpty()){int result = num.pop();printf("result = %d\n", result);}else{while (0==ope.isEmpty()){char m = ope.pop();int a = num.pop();//取出操作数栈中的两个数int b = num.pop();int c = caculate(a, b, m);//计算结果num.push(c);}int result = num.pop();printf("ans = %d\n", result);}system("pause");return 0;}

十进制转八进制主程序如下:

#include <iostream>#include "Stack.h"using namespace std;int main(){Stack s;    int m,n,k;cout<<"请输入一个十进制数:";cin>>k;while (k!=0){m=k%8;s.push(m);k=k/8;}cout<<"转换后的八进制数为:";while (s.isEmpty()==0){n=s.pop();cout<<n;}cout<<endl;return 0;}


堆栈类的结构如下:


//Stack.h

#pragma oncestruct node{char data;struct node *next;};class Stack{/*char space[100];int top;*/node *head;public:Stack();~Stack();void push(char c);char pop();int isEmpty();};
//Stack.cpp

#include "Stack.h"#include <stdlib.h>Stack::Stack(){//top = -1;head = NULL;}Stack::~Stack(){}void Stack::push(char c){//top++;//space[top] = c;node *temp;temp = (node*)malloc(sizeof(node));temp->data = c;temp->next = head;head = temp;}char Stack::pop(){//char c = space[top];//top--;//return c;node *temp;temp = head;head = head->next;char c = temp->data;return c;}int Stack::isEmpty(){return (head == NULL);//return( -1 == top);}



0 0