数据结构学习录(二)——用栈做出一个简单计算器1 C程序
本程序只适用于整数,稍后会继续增加浮点数
建立两个栈,一个存放数字,一个存放符号
借鉴大佬的,然后自己稍稍做了一些修改。
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int date;
struct node *next;
}Node;
typedef struct stack
{
Node *top;
int count;
}Stack;
int LinkStackInit(Stack **s) //申请空间
{
if(s == NULL)
{
return 0;
}
(*s) = (Stack *)malloc(sizeof(Stack) * 1);
if(*s == NULL)
{
return 0;
}
(*s) -> top = NULL;
(*s) -> count = 0;
return 1;
}
int LinkStackEmpty(Stack *s) //是否为空
{
if(s == NULL)
{
return 0;
}
return (s->top == NULL)?1: 0;
}
int Push(Stack **s, int e) //入栈
{
if(s == NULL)
{
return 0;
}
if((*s) == NULL)
{
return 0;
}
Node *p = (Node *)malloc(sizeof(Node));
p -> date = e;
p -> next = (*s) -> top;
(*s) -> top = p;
(*s) -> count++;
return 1;
}
int GetTop(Stack *s) //获取栈顶元素
{
if(s == NULL || s->top == NULL)
{
return ;
}
return s->top->date;
}
int Pop(Stack **s) //出栈
{
int e;
Node *p = (*s) -> top;
if(s == NULL || (*s) == NULL)
{
return 0;
}
e = (*s) -> top -> date;
(*s) -> top = (*s) -> top -> next;
(*s) -> count--;
free(p);
return e;
}
int Priority(char ch) //符号优先级判定
{
switch(ch)
{
case '(':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
int main()
{
Stack *s_char, *s_num; //建立两个栈,s_char用来放计算符号,s_num用来放还原后的数字
char input[1000] = {0}; //用来存放输入的表达式
int i = 0, temp = 0, num1 = 0, num2 = 0;
if(!LinkStackInit(&s_char) || !LinkStackInit(&s_num)) //判断栈的空间获取是否成功
{
printf("栈申请失败 \n");
}
printf("请输入表达式:(请输入英文状态下的符号) \n"); //输入表达式
scanf("%s",input);
while(input[i] != '\0' || !LinkStackEmpty(s_char) )
{
if(input[i] >= '0' && input[i] <= '9') //判断输入的是否为数字 还原数字
{
temp = temp * 10 + input[i] - '0';
i++;
if(input[i] > '9' || input[i] < '0') //当输入的下一个值不是数字时
{
Push(&s_num, temp); //将计算好的temp放入s_num中
temp = 0;
}
}
else
{
if((input[i] == ')') && (GetTop(s_char) == '(')) //如果此时的符号为 ( 且符号栈中的最上面的是 ) ,将 ) 弹出
{
Pop(&s_char);
i++;
continue;
}
if((LinkStackEmpty(s_char)) || (Priority(input[i]) > Priority(GetTop(s_char))) ||( (GetTop(s_char) == '(') && (input[i] != ')'))) //输入符号
{
Push(&s_char, input[i]);
i++;
continue;
}
if( ((input[i] == '\0') && !LinkStackEmpty(s_char) ) || ( (input[i] == ')') && (GetTop(s_char) != '(') )||(Priority(input[i]) <= Priority(GetTop(s_char)))) //进行计算
{
switch(Pop(&s_char))
{
case'+': num1 = Pop(&s_num); num2 = Pop(&s_num); Push(&s_num, (num2 + num1)); break;
case'-': num1 = Pop(&s_num); num2 = Pop(&s_num); Push(&s_num, (num2 - num1)); break;
case'*': num1 = Pop(&s_num); num2 = Pop(&s_num); Push(&s_num, (num2 * num1)); break;
case'/': num1 = Pop(&s_num); num2 = Pop(&s_num); Push(&s_num, (num2 / num1)); break;
}
}
}
}
printf("%d \n",GetTop(s_num)); //输出
return 0;
}
附上大佬原文,具有C and C++:
题目:C/C++计算器(栈的应用)
作者: 海都是水
文章链接:https://blog.csdn.net/sinat_39440759/article/details/82821200