"Data Structure Learning and Experiment Guide" 3-2: Non-recursive implementation of Hanoi

Source: Internet
Author: User
Tags printf


Experimental content: Using the stack to solve the Hanoi tower problem in a non-recursive way, the n plates are moved from the starting column through the column to the target column, and each movement is guaranteed to meet the Hanoi tower problem.
Input Description: The input is a positive integer n, which is the number of disks on the starting bar.
Output Description: One row for each operation, output in the format of column 2, bar 1.
Test Case:
Input | output
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;
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.