C语言中的递归,你真的懂了吗?

  #include

  /*柔性数组*/

  typedef struct _soft_array{

  int len;

  int array[];

  }soft_array;

  /*汉诺塔结构体*/

  typedef struct _hannuo{

  soft_array *p_data;

  char name;

  }hannuo;

  hannuo * han_a = NULL;

  hannuo * han_b = NULL;

  hannuo * han_c = NULL;

  void hannoiii(int n,hannuo * a,hannuo * b,hannuo * c);

  void moveiii (int n,hannuo * a,hannuo * c);

  int total;

  void printf_han_data(hannuo * han)

  {

  int i = 0;

  printf("%c: ",han->name);

  /*输出汉诺塔的数据*/

  for(i = 0;ip_data->len;i++)

  {

  printf("%d-",han->p_data->array[i]);

  }

  printf("

  ");

  }

  int main()

  {

  int i = 0;

  int n = 0;

  scanf(" %d",&n);

  total = n;

  /*定义三个汉诺塔节点*/

  han_a = (hannuo *)malloc(sizeof(hannuo));

  han_a->name = 'A';

  han_a->p_data = (soft_array*)malloc(sizeof(soft_array)+sizeof(int)*n);

  han_a->p_data->len = n;

  /*数据原来在第一根柱子上*/

  for(i = 0;i

  {

  han_a->p_data->array[i] = i+1;

  }

  printf_han_data(han_a);

  /*初始化第二根柱子*/

  han_b = (hannuo *)malloc(sizeof(hannuo));

  han_b->name = 'B';

  han_b->p_data = (soft_array*)malloc(sizeof(soft_array)+sizeof(int)*n);

  memset(han_b->p_data,0,sizeof(soft_array)+sizeof(int)*n);

  han_b->p_data->len = n;

  printf_han_data(han_b);

  /*初始化第三根柱子*/

  han_c = (hannuo *)malloc(sizeof(hannuo));

  han_c->name = 'C';

  han_c->p_data = (soft_array*)malloc(sizeof(soft_array)+sizeof(int)*n);

  memset(han_c->p_data,0,sizeof(soft_array)+sizeof(int)*n);

  han_c->p_data->len = n;

  printf_han_data(han_c);

  printf("------------------------

  ");

  hannoiii(n,han_a,han_b,han_c);

  printf("

  ");

  return 0;

  }

  void hannoiii(int n,hannuo * a,hannuo * b,hannuo * c)

  {

  if(n == 1)

  {

  a->p_data->array[0] = 0;

  c->p_data->array[0] = 1;

  printf_han_data(han_a);

  printf_han_data(han_b);

  printf_han_data(han_c);

  printf("------------------------

  ");

  }

  else

  {

  hannoiii(n - 1, a, c, b);/*把 n-1 从 a 柱子放到 b 柱子上面*/

  moveiii(n, a, c); /*把 n 从 a 移动到 c 上*/

  printf_han_data(han_a);

  printf_han_data(han_b);

  printf_han_data(han_c);

  printf("------------------------

  ");

  hannoiii(n - 1, b, a, c);/*把n - 1 通过 a 的辅助作用 从 b 移动到 c 上*/

  }

  }

  void moveiii (int n,hannuo * a,hannuo * c)

  {

  int i = 0;

  int tmp = a->p_data->array[n-1];

  a->p_data->array[n-1] = 0;

  #if 1

  c->p_data->array[n-1] = tmp;

  #else

  for(i = 0;i < total;i++)

  {

  if(c->p_data->array[i] == 0){

  c->p_data->array[i] = tmp;

  break;

  }

  }

  #endif

  }