汉诺塔(栈的应用)

#include <stdio.h>

#define NUM 9  //定义每个柱子最多能放的盘子数(即栈的大小)

struct stick

{

int stick[NUM];

int index;

} hn[3] = {

{{5, 4, 3, 2, 1}, 5},

{{}, 0},

{{}, 0}

};

static draw(void)

{

int i, index;

for(index = 0; index < 3; index++)

{

for(i = 0; i < NUM && i < hn[index].index; i++)

{

printf(“%d”, hn[index].stick[i]);

}

printf(“-\n”);

}

}

static int pop(int index)

{

int plate;

hn[index].index–;

plate = hn[index].stick[hn[index].index];

return plate;

}

static void push(int index, int plate)

{

hn[index].stick[hn[index].index] = plate;

hn[index].index++;

}

static void move(int src, int dest)

{

int plate;

plate = pop(src);

push(dest, plate);

draw();

getchar();

}

void hanoi(int src, int dest, int tmp, int n)

{

if(n == 1)

{

move(src, dest);

return;

}

hanoi(src, tmp, dest, n – 1);

move(src, dest);

hanoi(tmp, dest, src, n – 1);

}

int main(void)

{

draw();

hanoi(0, 2, 1, 5);

draw();

return 0;

}

    原文作者: 汉诺塔问题
    原文地址: https://blog.csdn.net/lqblog/article/details/9964667
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞