|
阅读:2392回复:3
Hanoi塔的非递归化
#include <stdio.h>
#include <alloc.h> typedef struct { int n; char a, b, c; int retAdd; } datatype; typedef struct t_listNode { datatype data; struct t_listNode * next; } listNode; void freeList(listNode *p) { if(p->next==NULL) return; freeList(p->next); free(p->next); } void push(listNode *s, int retAdd, int n, char a, char b, char c) /***** * *s is a list with head node *****/ { listNode *nd=(listNode *)malloc(sizeof(listNode)); nd->data.retAdd = retAdd; nd->data.n = n; nd->data.a = a; nd->data.b = b; nd->data.c = c; nd->next = s->next; s->next = nd; } void pop(listNode *s) { listNode *next = s->next; s->next = next->next; free(next); } datatype * top(listNode *s) { return &(s->next->data); } void hanoi(int n, char a, char b, char c) { if(n==1) printf("disk %d %c ==> %c", 1, a, c); else { hanoi(n-1, a, c, b); printf("disk %d %c ==> %c", n, a, c); hanoi(n-1, b, a, c); } } void main() { listNode *s = (listNode *)malloc(sizeof(listNode)); printf("============================\n"); /* hanoi(3, 'a', 'b', 'c'); */ s->next = NULL; push(s, 0, 3, 'a', 'b', 'c'); goto add100; add0: free(s); exit(0); add100: /* if(n==1) */ if(top(s)->n == 1) /* printf("%c ==> %c \n", a, c); */ printf("disk 1 %c ==> %c \n", top(s)->a, top(s)->c); else { /* hanoi(n-1, a, c, b); */ push(s, 102, top(s)->n-1, top(s)->a, top(s)->c, top(s)->b); goto add100; add102: /* printf("%c ==> %c \n", a, c); */ printf("disk %d %c ==> %c \n", top(s)->n, top(s)->a, top(s)->c); /* hanoi(n-1, b, a, c); */ push(s, 104, top(s)->n-1, top(s)->b, top(s)->a, top(s)->c); goto add100; } add104: switch(top(s)->retAdd) { case 102: pop(s); goto add102; case 104: pop(s); goto add104; case 0: pop(s); goto add0; } } [ 2001-7-7 12:06:26 Hades 修改 ] |
|
|
1C#
发布于:2001-06-12 17:02
好
欢迎 Hades 多发这样的帖子。 |
|
|
|
3C#
发布于:2001-06-25 14:56
Re:你就知道好
要什么好的?一般都难得带有算法在里面,又不是商业程序,写写玩完的。再说也不是很长,慢慢看吧,老兄;)
顺便我在这里提出个算法问题:有两个杯子,一大一小。然后给定你一个需要的体积。问能否有着两个杯子倒腾出给顶的体积来(注意不能用别的杯子帮忙哟):rolleyes::rolleyes::rolleyes:: -------------------- Optimistic is my color We spend our time on something from dawn to dark Day in and day out Sun rise and down Make an own goal to confront life Self-discovery is the first step toward self-appreciation 成功只会降临在自认为会成功的人身上 |
|