fork(2) download
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3. #include<string.h>
  4.  
  5. void hanoi(int n, int *from, int *mid, int *to);
  6. void push(int value, int *top);
  7. int pop(int *top);
  8. void print(char plate, int h[], int n);
  9.  
  10. int k, n;
  11. int *a, *b, *c; //製作三個堆疊用
  12. int *top_a, *top_b, *top_c;
  13.  
  14. int main()
  15. {
  16. int i;
  17.  
  18. scanf("%d",&n);
  19. k = n;
  20.  
  21. a = (int*)malloc(sizeof(int)*n);
  22. b = (int*)malloc(sizeof(int)*n);
  23. c = (int*)malloc(sizeof(int)*n);
  24. memset(a, 0, sizeof(int)*n);
  25. memset(b, 0, sizeof(int)*n);
  26. memset(c, 0, sizeof(int)*n);
  27. top_a = a;
  28. top_b = b;
  29. top_c = c;
  30.  
  31. for(i = 0; i < n; i++)
  32. {
  33. *top_a = k;
  34. if(i != n-1)
  35. top_a++;
  36. k--;
  37. }
  38.  
  39. k = n;
  40. hanoi(n, top_a, top_b, top_c);
  41. return 0;
  42. }
  43.  
  44. void hanoi(int n, int *from, int *mid, int *to)
  45. {
  46. if(n == 0)
  47. return ;
  48. hanoi(n-1, from, to, mid);
  49. push(pop(from),to);
  50. print('A', a, k);
  51. print('B', b, k);
  52. print('C', c, k);
  53. printf("\n");
  54. hanoi(n-1, mid, from, to);
  55. }
  56.  
  57. void push(int value, int *top)
  58. {
  59. *top = value;
  60. top++;
  61. }
  62.  
  63. int pop(int *top)
  64. {
  65. int temp;
  66.  
  67. if(*top == -1 ) //判斷堆疊是否為空的
  68. return -1;
  69. temp = *top;
  70. *top = 0;
  71. top--;
  72. return temp;
  73. }
  74.  
  75. void print(char plate, int h[], int n)
  76. {
  77. int i;
  78. printf("Tower %c: ",plate);
  79. for(i = 0; i < n; i++)
  80. printf("%d ",h[i]);
  81. printf("\n");
  82. }
Success #stdin #stdout 0s 4352KB
stdin
Standard input is empty
stdout
Standard output is empty