汉诺塔

来源:互联网 发布:人工智能程序如何编写 编辑:程序博客网 时间:2024/06/06 12:41

#include <stdio.h>#include <stdlib.h>typedef int T;#define NUM 4struct stack{int size;int index;T *head;};int init(struct stack *p, int n);void destroy(struct stack *p);int get_size(struct stack *p);int get_index(struct stack *p);int push(struct stack *p, const T *pt);int pop_(struct stack *p);T gettop(struct stack *p);T pop(struct stack *p);void move(struct stack *pa, struct stack *pb, struct stack *pc, int n);void print(struct stack *p);struct stack a,b,c;int main(){int i;// 1init(&a, NUM);init(&b, NUM);init(&c, NUM);for(i=0; i<NUM; i++){int x=NUM-i;push(&a, &x);}printf("Start pa :\n");print(&a);// 2move(&a,&b,&c,NUM);//3printf("Result :\n");print(&b);destroy(&a);destroy(&b);destroy(&c);return 0;}//////////////////////////////int init(struct stack *p, int n){p->size=n;p->index=-1;p->head = (T*)malloc(n * sizeof(T));if(p->head == NULL)return -1;elsereturn 0;}void destroy(struct stack *p){p->size=0;p->index=-1;free(p->head);p->head = NULL;}int get_size(struct stack *p){return p->size;}int get_index(struct stack *p){return p->index;}int push(struct stack *p, const T *pt){p->index++;if(p->index < p->size){p->head[p->index] = *pt;}else{T *pp;pp=(T*)realloc(p->head, 2*p->size*sizeof(T));if(pp==NULL)return -1;p->head = pp;p->head[p->index] = *pt;}return 0;}int pop_(struct stack *p){if(p->index<0)return -1;elsep->index--;return 0;}T gettop(struct stack *p){return p->head[p->index];}T pop(struct stack *p){T t=gettop(p);pop_(p);return t;}// pa -> pb ,using pcvoid move(struct stack *pa, struct stack *pb, struct stack *pc, int n){T t;if (n<0)return;if(n==1){t=pop(pa);push(pb,&t);printf("move %d %x -> %x\n", t, pa, pb);}else{move(pa, pc, pb, n-1);t=pop(pa);push(pb,&t);printf("move %d %x -> %x\n", t, pa, pb);move(pc, pb, pa, n-1);}return;}void print(struct stack *p){int i;for(i=0; i<p->size; i++){printf("%d\n", p->head[i]);}}