gpt4 book ai didi

c - 需要插入单链表的帮助

转载 作者:行者123 更新时间:2023-11-30 18:06:14 24 4
gpt4 key购买 nike

    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;
}
}
}

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

最佳答案

更改以下内容:

    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;
}

关于c - 需要插入单链表的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5763401/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com