本文主要是介绍用两个栈实现简单的四则运算,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目要求:给定一个字符串如“1+2*3”,没有括号,要求利用栈的知识来处理结果算出答案
我的思路:建立两个栈,一个存放数据,一个存放符号,再定义一个结构体做为操作的主体,然后制作几个函数,分别承担栈的基本操作,比较优先级,数学计算等功能。入栈时,如果是数字,则直接入栈,如果是符号,则先判断栈是否为空,如果为空则直接入栈,如果不为空则先与栈顶字符比较优先级,如果优先级低于栈顶字符,则从数字栈中弹出顶端的两个值,从符号栈中弹出一个值先完成计算,然后再入到数字栈中,如果优先级高于栈顶字符,再入栈,最后再统一运算
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct
{int *data;int top;
}zhan;
typedef struct
{char* data;int top;
}fu;
typedef struct
{zhan* num;fu*sign;
}yunsuan;
zhan* creatzhan()
{zhan* point = (zhan*)malloc(sizeof(zhan));point->data = (int*)malloc(sizeof(char) * 100);point->top = -1;return point;
}
fu* creatfu()
{fu* point = (fu*)malloc(sizeof(zhan));point->data = (char*)malloc(sizeof(char) * 100);point->top = -1;return point;
}
yunsuan* creatyunsuan()
{yunsuan* good = (yunsuan*)malloc(sizeof(yunsuan));good->num = creatzhan();good->sign = creatfu();return good;
}
int judgezhan(zhan* point)
{if (point->top == -1)\{return -1;}return 1;
}
int judgefu(fu* point)
{if (point->top == -1)\{return -1;}return 1;
}
void pushnum(yunsuan*point,int num1)
{point->num->data[++point->num->top] = num1;
}
void pushsign(yunsuan* point, char sign1)
{point->sign->data[++point->sign->top] = sign1;
}
void popnum(yunsuan* point)
{int p = judgezhan(point->num);if (p != -1)point->num->top--;
}
void popsign(yunsuan* point)
{int p = judgefu(point->sign);if (p != -1)point->sign->top--;
}
int topzhan(zhan* point)
{int p = judgezhan(point);if (p != -1){return point->data[point->top];}}
char topfu(fu* point)
{int p = judgefu(point);if (p != -1){return point->data[point->top];}}
int youxianji(char x)
{if (x == '+' || x == '-'){return 1;}else{return 2;}
}
int compare(int first, int next)
{if (first <= next){return 1;}else{return 2;}
}
int conclude(int num1, int num2, char ch)
{int result=0;switch (ch){case '+': {result =result+ num2 + num1;break;}case '-': {result =result+ num2 - num1;break;}case '*': {result =result+ num2 * num1;break;}case '/': {result = result+num2 / num1;break;}}return result;
}
int main()
{char arr[] = { "1+2*3" };yunsuan* point = creatyunsuan();int x = 0;int total = 0;while (x != '\0'){if (x != '+' && x != '-' && x != '*' && x != '/'){pushnum(point, arr[x]-'0');x++;}else{do {if (judgefu(point->sign) == -1){pushsign(point, arr[x]);x++;}else{if (compare(youxianji(topfu(point->sign)), youxianji(arr[x])) == 1){pushsign(point, arr[x]);x++;}else{int a = topzhan(point->num);popnum(point);int b = topzhan(point->num);popnum(point);char c = topfu(point->sign);popsign(point);int f = conclude(a, b, c);pushnum(point, f);}}} while (compare(topfu(point->sign), arr[x]) == 1);}}while (judgefu(point->sign) && judgezhan(point->num)){int a1 = topzhan(point->num);popnum(point);int b1 = topzhan(point->num);popnum(point);char c1 = topfu(point->sign);popsign(point);int f1 = conclude(a1, b1, c1);total = total + f1;pushnum(point, f1);}printf("%d", total);return 0;
}
出了问题但找不到解决方法,求大佬帮助
这篇关于用两个栈实现简单的四则运算的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!