LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
12
返回列表 发新帖
楼主: Illidan

这个错我真是想不明白啊

[复制链接]
 楼主| 发表于 2005-9-19 15:27:50 | 显示全部楼层
Post by herberteuler
为什么对 fourth 调用 list_add 时使用 3 呀?能不能贴一下 list_add 的代码?

我对list_add的位置参数规定是:非负整数,0表示表尾,1表示第一个结点,n的意思是插入原来第n个结点前面,也就是插入的结点会成为新的第n个结点。
    第1帖那段测试代码,是把四个节点插入到单向链表中,位置参数是随意的。
    以下是一个接口的定义。有什么缺点的话,请指正。


  1. void list_add(field_list_t* list, node_t* node, int pos)
  2. {
  3.         char* fn = "list_add";
  4.         if (list==NULL)
  5.         {
  6.                 fprintf( stderr, "%s: list not allocated. unable to add.\n", fn );
  7.                 return;
  8.         }
  9.         if (pos<0)
  10.         {
  11.                 fprintf( stderr, "%s: required position invalid.\n", fn );
  12.                 return;
  13.         }
  14.         if ( (list->num_node!=0) && (pos >= list->num_node+2) )
  15.         {
  16.                 fprintf( stderr, "%s: out of list  bound\n", fn);
  17.                 return;
  18.         }
  19.         if (list->num_node==0 && pos<=1) //node becomes the only element in the list
  20.         {
  21.                 list->rear = node;
  22.                 list->head = list->rear;
  23.                 list->num_node ++;
  24.                 return;
  25.         }
  26.         if ( (pos == 0) || (pos-(list->num_node) == 1) ) //the special postion 0 means the rear
  27.         {
  28.                 list->rear->next = node;
  29.                 list->rear = node;
  30.                 list->rear->next = NULL;
  31.                 (list->num_node)++;
  32.                 return;
  33.         }
  34.         if (pos==1) //node becomes the new head
  35.         {
  36.                 node->next = list->head;
  37.                 list->head = node;
  38.                 (list->num_node)++;
  39.                 return;
  40.         }

  41.         node_t* ptr = list->head;

  42.        int i;
  43.         for (i=1; i<=pos-2; i++)
  44.         {
  45.                 ptr = ptr->next;
  46.         }
  47.         node->next = ptr->next;
  48.         ptr->next = node;
  49.         (list->num_node)++;
  50. }
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表