《数据结构学习与实验指导》3-2:汉诺塔的非递归实现

来源:互联网 发布:易语言验证码识别源码 编辑:程序博客网 时间:2024/06/06 01:16

实验内容:借助堆栈以非递归方式求解汉诺塔问题,即将n个盘子从起始柱通过借助柱移动到目标柱,并保证每个移动符合汉诺塔问题要求。
输入说明:输入为一个正整数n,即起始柱上的盘数。
输出说明:每个操作占一行,按“柱1 -> 柱2“的格式输出。
测试用例:
输入 | 输出
1 | a -> c
2 | a -> b
a -> c
b ->c
3 | a -> c
a -> b
c -> b
a -> c
b -> a
b -> c
a -> c

#include <stdio.h>#include <stdlib.h>typedef struct Node {    int n;    char from;    char pass;    char to;    struct Node *previous;} *PNode;typedef struct {    PNode top;} *PStack;PStack init();PNode pop(PStack stack);void push(PStack stack, int n, char from, char pass, char to);int main() {    int N;    scanf("%d", &N);    PStack stack = init();    push(stack, N, 'a', 'b', 'c');    while (stack->top != NULL) {        PNode node = pop(stack);        if (node->n == 1) {            printf("%c -> %c\n", node->from, node->to);        } else {            push(stack, node->n - 1, 'b', 'a', 'c');            push(stack, 1, 'a', 'b', 'c');            push(stack, node->n - 1, 'a', 'c', 'b');        }    }    printf("%d\n", count);}PStack init() {    PStack stack = (PStack) malloc(sizeof(PStack));    stack->top = NULL;    return stack;}PNode pop(PStack stack) {    PNode top = stack->top;    if (top == NULL) {        return NULL;    }    PNode p = top;    stack->top = p->previous;    return p;}void push(PStack stack, int n, char from, char pass, char to) {    PNode node = (PNode) malloc(sizeof(PNode));    node->n = n;    node->from = from;    node->pass = pass;    node->to = to;    node->previous = stack->top;    stack->top = node;}
阅读全文
0 0