数据结构之栈的应用(1) 用栈模拟Hanoi塔
来源:互联网 发布:上海网络综合布线工程 编辑:程序博客网 时间:2024/06/06 00:57
在Lintcode算是简单题了 九章算法给的C++版本的 这里提供C语言版的供参考
#include#include #define ERROR 0;#define OK 1;typedef struct Stack{ int *elements; int max_size,top_index;}Stack;void init(Stack *s,int length){ s->elements=(int *)malloc(sizeof(int)*length); s->max_size=length; s->top_index=-1;}int push(Stack* s, int element){ if (s->top_index >= s->max_size - 1) { return ERROR; } s->top_index++; s->elements[s->top_index] = element; return OK;}int pop(Stack* s){ if(s->top_index < 0){ return ERROR; } s->top_index--; return OK;}int top(Stack* s) { if(s->top_index==-1){ return ERROR; } else{ return s->elements[s->top_index]; }}int empty(Stack* s){ if(s->top_index < 0){ return 1; } else{ return 0; }}void movetop(Stack *A, Stack* t){ int topone=top(A); pop(A); push(t,topone);}void movehanoi(int n,Stack *A,Stack* buffer,Stack* destination){ if(n==1){ movetop(A,destination); } else{ movehanoi(n-1,A,destination,buffer); movetop(A,destination); movehanoi(n-1,buffer,A,destination); }}int main(){ int n; scanf("%d",&n); Stack* stack_a=(Stack *)malloc(sizeof(Stack)); init(stack_a,n); Stack* stack_b=(Stack *)malloc(sizeof(Stack)); init(stack_b,n); Stack* stack_c=(Stack *)malloc(sizeof(Stack)); init(stack_c,n); for(int i=n;i>=1;i--){ push(stack_a,i); } movehanoi(n, stack_a, stack_b, stack_c); for(int i=1;i<=n;i++){ printf("%d\n",top(stack_c)); pop(stack_c); }}
阅读全文
0 0
- 数据结构之栈的应用(1) 用栈模拟Hanoi塔
- 栈的应用之hanoi问题
- 数据结构的应用——使用栈和递归实现Hanoi问题求解
- 栈和递归的应用:Hanoi问题
- 数据结构C语言版之Hanoi塔问题
- 栈和递归之Hanoi塔
- 数据结构:栈与递归(Hanoi塔问题)
- 数据结构之栈的应用
- 数据结构之 栈的应用
- C++ 数据结构 hanoi 汉诺塔(递归 栈)
- 数据结构-Hanoi塔问题
- 数据结构之用栈模拟队列
- 【数据结构】 栈的模拟
- hanoi塔基于栈的递归实现
- 简单数据结构之栈模拟
- 012.栈应用Hanoi递归C实例
- hanoi塔问题模拟程序
- 数据结构栈的应用之括号匹配
- 【TP】【P-sensor】TP模拟P-sensor
- sql语句实现的具体过程
- 软件测试实验室之Eclipse
- python Django web初学安装
- eclipse中如何正确打开对应格式的文件比如.ftl , .bpmn等
- 数据结构之栈的应用(1) 用栈模拟Hanoi塔
- Python+Hadoop Streaming实现MapReduce(如何给map和reduce的脚本传递参数)
- [wiki--gitit]在Linux系统搭建gitit wiki
- JDBC使用 PreparedStatement 比使用 Statement 的好处
- Zookeeper学习之集群环境搭建
- Java代码优化(长期更新)
- laravel在中间件内生成参数并且传递到控制器2种姿势
- C++模板函数
- 正则表达式 平衡组/递归匹配