博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用栈计算逆波兰式
阅读量:2350 次
发布时间:2019-05-10

本文共 2679 字,大约阅读时间需要 8 分钟。

#include 
#include
#include
typedef struct Mystack *Stack;struct Mystack { int Capacity; /* 栈的容量 */ int Top_of_stack; /* 栈顶下标 */ int *Array; /* 存放栈中元素的数组 */};/* 栈的创建 */Stack CreateStack(int Max){ Stack S; S = malloc(sizeof(struct Mystack)); if (S == NULL) printf("Create stack error!\n"); S->Array = malloc(sizeof(char) * Max); if (S->Array == NULL) printf("Create stack error!\n"); S->Capacity = Max; S->Top_of_stack = 0; return S;}/* 释放栈 */void DisposeStack(Stack S){ if (S != NULL) { free(S->Array); free(S); } }/* 判断一个栈是否是空栈 */int IsEmpty(Stack S){ return !S->Top_of_stack;}/* 判断一个栈是否满栈 */int IsFull(Stack S){ if (S->Top_of_stack == S->Capacity - 1) return 1; else return 0;}/* 数据入栈 */int Push(int x, Stack S){ if (IsFull(S)) printf("The Stack is full!\n"); else S->Array[S->Top_of_stack++] = x;}/* 数据出栈 */int Pop(Stack S){ if (IsEmpty(S)) printf("The Stack is empty!\n"); else S->Top_of_stack--;}/* 将栈顶返回 */int Top(Stack S){ if (!IsEmpty(S)) return S->Array[S->Top_of_stack-1]; printf("The Stack is empty!\n"); return 0;}int main(){ int i, len, result; char str[100]; printf("Please input the postfix that you want to compute: \n"); scanf("%s", str); len = strlen(str); /* 根据序列的长度来创建栈 */ struct Mystack *my_stack = CreateStack(len+1); for (i = 0; i < len; i++) { if (str[i] >= '0' && str[i] <= '9') Push((int)str[i]-48, my_stack); else if (str[i] == '+') { int x = Top(my_stack); Pop(my_stack); int y =Top(my_stack); Pop(my_stack); Push(x+y, my_stack); //printf("%d\n", Top(my_stack)); } else if (str[i] == '-') { int x = Top(my_stack); Pop(my_stack); int y = Top(my_stack); Pop(my_stack); Push(x-y, my_stack); //printf("%d\n", Top(my_stack)); } else if (str[i] == '*') { int x = Top(my_stack); Pop(my_stack); int y = Top(my_stack); Pop(my_stack); Push(x*y, my_stack); //printf("%d\n", Top(my_stack)); } else if (str[i] == '/') { int x = Top(my_stack); Pop(my_stack); int y = Top(my_stack); Pop(my_stack); Push(x/y, my_stack); //printf("%d\n", Top(my_stack)); } } printf("The result is: %d\n", Top(my_stack)); Pop(my_stack); /* A bug */// DisposeStack(my_stack); return 0;}

转载地址:http://kphvb.baihongyu.com/

你可能感兴趣的文章
S3C6410 存储器映射
查看>>
Linux 3.3.0移植到S3C6410开发板上之一
查看>>
Busybox支持中文的解决办法
查看>>
Spring中BeanFactory和FactoryBean有什么区别?
查看>>
牛年(2021)的KPI
查看>>
快速识别图片类型
查看>>
理解云原生
查看>>
docker常见问题答疑
查看>>
mac最简配置maven
查看>>
虚拟机性能监控与故障处理工具
查看>>
GIT的一些操作
查看>>
ZooKeeper 四字命令
查看>>
Mysql InnoDB锁问题
查看>>
ZooKeeper编程 基础教程
查看>>
Java 集合框架
查看>>
kafka 操作
查看>>
Java 集合框架 算法
查看>>
Java 集合框架 Set实现
查看>>
Java 集合框架 List实现
查看>>
Java 集合框架 Map 实现
查看>>