gpt4 book ai didi

C 两个链表的追加和排序

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

我有一个函数,它应该接受两个链接列表并将它们放在一起。

    void Append(struct node** aRef, struct node** bRef){
struct node* first = *aRef;
struct node* second = *bRef;
struct node* temp = NULL;

while(first != NULL || second != NULL){
Push(&temp, first->data);
Push(&temp, second->data);
first = first->next;
second = second->next;
}

*aRef = temp;
DeleteList(&second);
}

我想对其进行排序,但当我用以下替换 while 循环时,我不断遇到段错误:

while(first != NULL || second != NULL){
if(first->data < second->data){
Push(&temp, first->data);
first = first->next;
}
else{
Push(&temp, second->data);
second = second->next;
}
}

Push() 函数只是将一些数据添加到结构节点:

void Push(struct node** headRef, int data){
struct node* new = malloc(sizeof(struct node));
new->data = data;
new->next = *headRef;
*headRef = new;
}

struct node{
int data;
struct node* next;
};

最佳答案

这可以解决您的问题。因为如果不测试两者,就无法执行第一次比较。

while(first != NULL || second != NULL){
if((first != NULL && second != NULL && first->data < second->data) || (first != NULL && second == NULL)){
Push(&temp, first->data);
first = first->next;
}
else if (second != NULL) {
Push(&temp, second->data);
second = second->next;
}
}

关于C 两个链表的追加和排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7922111/

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