栈的应用 ——计算器
来源:互联网 发布:java常见的接口 编辑:程序博客网 时间:2024/04/29 17:05
计算器即是四则运算法则:
我们用的是后缀表达式又称逆波兰的方法实现的,例如我们来求9+(3-1)X3+10/2
后缀表达式为931-3*+102/+
规则是从左往右遍历表达式的每个数字和符号,遇到数字就进栈,遇到符号就将处于栈顶两个数字出栈,进行运算,一直到最终获得结果。
#include <stdio.h>
#include <stdlib.h>#define OK 10000001
#define ERROR 10000002
struct node
{
int data;
struct node *next;
};
typedef struct node Node;
struct stack
{
Node *top;
int count;
};
typedef struct stack Stack;
int InitStack(Stack *S)
{
S->top = NULL;
S->count = 0;
return OK;
}
int EmptyStack(Stack *S)
{
return (S->count == 0) ? OK :ERROR;
}
int Push(Stack *S,int e)
{
Node *p = (Node *)malloc(sizeof(Node));
if(p == NULL)
{
return ERROR;
}
p->data = e;
p->next = S->top;
S->top = p;
S->count++;
return OK;
}
int GetTop(Stack *S)
{
if(NULL == S->top)
{
return ERROR;
}
return (S->top->data);
}
int Priority(char s)
{
switch(s)
{
case '(':
return 3;
case '*':
case '/':
return 2;
case '+':
case '-':
return 1;
default:
return 0;
}
}
int Pop(Stack *S)
{
int e;
if(NULL == S->top)
{
return ERROR;
}
Node *p = S->top;
e = p->data;
S->top = p->next;
free(p);
S->count--;
return e;
}
int main()
{
Stack num,opt;
char str[100] = {0};
int i = 0, tmp = 0, j;
if(InitStack(&num) != OK ||InitStack(&opt) != OK)
{
printf("Init Failure!!\n");
}
printf("Please Input Operator :\n");
scanf("%s",str);
while (str[i] != '\0' || EmptyStack(&opt) != OK)
{
if (str[i] >= '0' && str[i] <= '9')
{
tmp = tmp * 10 + str[i] - '0';
i++;
if(str[i] < '0' || str[i] > '9')
{
Push(&num,tmp);
tmp = 0;
}
}
else
{
if((EmptyStack(&opt) == OK) || (GetTop(&opt) == '(' && str[i] !=')') || Priority( str[i]) > Priority(GetTop(&opt)))
{
Push(&opt,str[i]);
i++;
continue;
}
if(GetTop(&opt) == '(' && str[i] == ')')
{
Pop(&opt);
i++;
continue;
}
if((str[i] == '\0' && EmptyStack(&opt) != OK) || (str[i] == ')' && GetTop(&opt) != '(') || Priority(str[i]) <= Priority(GetTop(&opt)))
{
switch(Pop(&opt))
{
case '+':
Push(&num,Pop(&num) + Pop(&num));
break;
case '-':
j = Pop(&num);
Push(&num,Pop(&num) - j);
break;
case '*':
Push(&num,Pop(&num) * Pop(&num));
break;
case '/':
j = Pop(&num);
Push(&num,Pop(&num) / j);
break;
}
continue;
}
}
}
printf("result is %d\n",Pop(&num));
return 0;
}
阅读全文
0 0
- 栈的应用 ——计算器
- 栈的应用——一个简单的整数计算器
- 栈的应用——计算器的四则运算
- c++ 数据结构 *** 栈的应用——计算器
- 栈的应用——实现简易计算器(一)
- 简易计算器实现混合运算——栈的应用
- 栈的应用 - 简单计算器
- iPhone应用开发——简易计算器的设计
- PHP编写的小应用——计算器
- 简单控件的应用(一)—prj计算器
- 用C#实现一个普通计算器——栈和队列的应用
- 简易计算器(栈的应用)
- 【数据结构】栈的应用之表达式计算器
- 栈的应用--简单计算器---加减乘除
- 栈的应用--计算器实现四则运算
- 计算器的介绍和应用
- 数据结构试验栈的应用,计算器的代码
- 栈的应用之简易计算器的实现
- 有人对他说:如果连 Python 都学不会,你就不要学编程了
- 采用Clone()方式创建对象
- 请关注我,点击关注!谢谢!
- Python机器学习实战:我的共享单车被谁骑走了?
- jFinal写的修改密码的具体实现
- 栈的应用 ——计算器
- 串的堆分配存储表示
- Docker 安装 RabbitMQ 集群
- liunx常用命令-01
- Locating Restriction Sites
- strong对象,替换 replace,将字符串1转化为字符串2
- 问题解决:DuplicateKeyException: a different object with the same identifier value
- Leetcode 算法设计 第十四周
- WebService返回XML文件自定义格式