C两个链表附加和排序

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

    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()函数只是将一些数据添加到struct节点:

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;
};
0
我刚刚意识到这甚至不会完全排序
额外 作者 Riz Baltazar,

3 答案

这解决了您的问题。因为如果你没有测试两者,你就无法进行第一次比较。

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;
      }
 }
2
额外
啊,好吧谢谢你。我应该听取老师的意见并编写测试计划
额外 作者 Riz Baltazar,
while(first != NULL || second != NULL ){

This will keep iterating as long as any of them is != NULL, so either you have to change your condition to && or check within the while body if either one of them is NULL.

0
额外

Since you're moving to the next nodes separately, one of them reaches NULL before the algorithm is finished. When this happens, your if condition crashes because your trying to access the data attribute of NULL

0
额外