需要有关插入单链表的帮助

时间:2011-04-23 09:25:00

标签: c

    void insert(SLL *list, Employee e){

   NODE *temp, *current, *temp2;

   temp = (NODE *)malloc(sizeof(NODE));
   assert(temp != NULL);

   temp -> anEmployee = (Employee *)malloc(sizeof(Employee));
   assert(temp -> anEmployee != NULL);

   strcpy(temp -> anEmployee -> name, e.name); 
   temp -> anEmployee -> ID = e.ID;
   strcpy(temp -> anEmployee -> address, e.address); 
   strcpy(temp -> anEmployee -> city, e.city);
   temp -> anEmployee -> age = e.age;

   temp -> next = NULL;

   if (list -> head == NULL) {     /* list is empty */
      list -> head = list -> tail = temp;
      return;
   }
   else { // list is not empty
        current = list-> head;
        while(current -> next != NULL && strcmp(temp-> anEmployee -> name, current-> anEmployee -> name)>0){
            current = current -> next;
        }
        if(current -> next == NULL){
            list -> tail -> next = temp;
            list -> tail = temp;
        }
        else{
            temp -> next = current -> next;
            current -> next = temp;
        }
  }
}

它正确地插入员工并将它们按照排序顺序排列,就像我想面对的唯一问题一样是列表中的第一个员工没有被排序。

1 个答案:

答案 0 :(得分:0)

更改以下内容:

    if(current -> next == NULL){
        list -> tail -> next = temp;
        list -> tail = temp;
    }
    else{
        temp -> next = current -> next;
        current -> next = temp;
    }

使用:

    if(current == list->head){
        list->head = temp;
        temp->next = current;
    } else if(current -> next == NULL){
        list -> tail -> next = temp;
        list -> tail = temp;
    } else{
        temp -> next = current -> next;
        current -> next = temp;
    }