|
|

楼主 |
发表于 2005-9-19 15:27:50
|
显示全部楼层
Post by herberteuler
为什么对 fourth 调用 list_add 时使用 3 呀?能不能贴一下 list_add 的代码?
我对list_add的位置参数规定是:非负整数,0表示表尾,1表示第一个结点,n的意思是插入原来第n个结点前面,也就是插入的结点会成为新的第n个结点。
第1帖那段测试代码,是把四个节点插入到单向链表中,位置参数是随意的。
以下是一个接口的定义。有什么缺点的话,请指正。
- void list_add(field_list_t* list, node_t* node, int pos)
- {
- char* fn = "list_add";
- if (list==NULL)
- {
- fprintf( stderr, "%s: list not allocated. unable to add.\n", fn );
- return;
- }
- if (pos<0)
- {
- fprintf( stderr, "%s: required position invalid.\n", fn );
- return;
- }
- if ( (list->num_node!=0) && (pos >= list->num_node+2) )
- {
- fprintf( stderr, "%s: out of list bound\n", fn);
- return;
- }
- if (list->num_node==0 && pos<=1) //node becomes the only element in the list
- {
- list->rear = node;
- list->head = list->rear;
- list->num_node ++;
- return;
- }
- if ( (pos == 0) || (pos-(list->num_node) == 1) ) //the special postion 0 means the rear
- {
- list->rear->next = node;
- list->rear = node;
- list->rear->next = NULL;
- (list->num_node)++;
- return;
- }
- if (pos==1) //node becomes the new head
- {
- node->next = list->head;
- list->head = node;
- (list->num_node)++;
- return;
- }
- node_t* ptr = list->head;
- int i;
- for (i=1; i<=pos-2; i++)
- {
- ptr = ptr->next;
- }
- node->next = ptr->next;
- ptr->next = node;
- (list->num_node)++;
- }
复制代码 |
|