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;
}