【问题标题】:C Two linked list append and sortC 两个链表追加和排序
【发布时间】:2011-10-27 20:41:45
【问题描述】:

我有一个函数应该把两个链表放在一起。

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

【问题讨论】:

  • 我刚刚意识到这甚至不能完全排序列表

标签: c sorting struct linked-list


【解决方案1】:

这解决了您的问题。因为如果两个都不测试,就无法进行第一次比较。

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】:
while(first != NULL || second != NULL ){

只要其中任何一个是!= NULL,这将继续迭代,因此您必须将条件更改为&amp;&amp;,或者在while 正文中检查其中一个是否为NULL

【讨论】:

    【解决方案3】:

    由于您要分别移动到 next 节点,因此其中一个节点会在算法完成之前到达 NULL。发生这种情况时,您的 if 条件会崩溃,因为您尝试访问 NULLdata 属性

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-08-11
      • 1970-01-01
      • 1970-01-01
      • 2012-04-20
      • 1970-01-01
      • 2018-07-14
      • 1970-01-01
      • 2021-12-20
      相关资源
      最近更新 更多