数据结构之栈的应用(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);    }}


原创粉丝点击