学习自:操作系统上的程序 - 南京大学jyy
#include<stdio.h>
#include<assert.h>
typedef struct {
int pc, n;
char from, to, via;
}Frame;
#define call(...) ({ *( ++ top) = (Frame){.pc = 0, __VA_ARGS__}; })
#define ret() ({ top --; })
#define goto(loc) ({ f->pc = (loc) - 1; })
void hanoi(int n, char from, char to, char via) {
Frame stk[64], *top = stk - 1;
call(n, from, to, via);
for (Frame *f = top; (f = top) >= stk; f->pc ++) {
switch (f->pc) {
case 0:
if (f->n == 1) {
printf("move %c -> %c\n", f->from, f->to);
ret();
}
break;
case 1:
call(f->n - 1, f->from, f->via, f->to);
break;
case 2:
printf("move %c -> %c\n", f->from, f->to);
break;
case 3:
call(f->n - 1, f->via, f->to, f->from);
break;
case 4:
ret();
break;
default:
assert(0);
}
}
}
int main()
{
hanoi(4, 'A', 'B', 'C');
return 0;
}
jyy yyds
jyy yyds
求关注
25天以来,头一次发文,捉
qwq