【问题标题】:Why is insert function always appending at end of linked list?为什么插入函数总是附加在链表的末尾?
【发布时间】:2016-12-17 05:53:20
【问题描述】:

我已编写此代码以按位置插入到链表中。

void insert(node *list, int data, int position) {
    int c;

    node *temp; 
    node *prev; 
    node *curr;

    curr = list;

    temp = malloc(sizeof(node));
    temp->num = data;

    if (curr == NULL) { 
        curr = temp;
        curr->next = NULL;
    } else { 
        while (curr != NULL && c != position) { 
            prev = curr;
            curr = curr->next;
            c++;
        }
        if (c = 0) { 
            temp->next = curr;
            curr = temp;
        } else if (curr == NULL) { 
            prev->next = temp;
        } else { 
            prev->next = temp;
            temp->next = curr;
        }
    }
}

但是,我相信这个块无论如何都会执行,并且数据会附加到链表的末尾。

else if (curr == NULL) { 
      prev->next = temp;

为什么curr 总是为空?如果位置小于列表中元素的数量,它不应该为 null...

【问题讨论】:

  • 首先:int c = 0;

标签: c data-structures linked-list


【解决方案1】:

一开始你还没有将 c 变量初始化为 0。还有条件 if(c = 0) 应该是 if(c == 0)

temp->next = NULL 也应该在 temp->num = data 之后完成,否则在

的情况下它将保持未初始化状态
      else if (curr==NULL) { 
               prev->next=temp;
      }

这些是我注意到的几个。

【讨论】:

    【解决方案2】:

    你有一个局部变量:c

    那个变量是自动存储的,它的起始值是不确定的。 你必须初始化它

    int c = 0;
    

    否则它的初始值可以是函数调用时的寄存器旧值或内存垃圾,所以

    while (curr!=NULL && c != position)
    

    行为未定义。


    此外,while 之后的 if 检查被窃听:相等的关系运算符是 ==

    if (c=0)
    

    必须

    if (c==0)
    

    否则,您会将0 分配给c,而不是测试其值。

    【讨论】:

      【解决方案3】:

      您的代码存在多个问题:

      • 局部变量c 未初始化。在没有事先初始化的情况下使用它会调用未定义的行为。你应该这样定义它:

        int c = 0;
        
      • 测试if (c = 0)c 的值设置为0 并且总是失败。请改用== 运算符:

        if (c == 0) {
            ...
        
      • 您必须返回 list 并将 list 设置为 curr 是元素被插入到列表的开头(位置 0)还是列表为空。

      这是一个改进的版本:

      node *insert(node *list, int data, int position) {
          node *temp = malloc(sizeof(node));
          if (temp == NULL) {
              return NULL;
          }
          temp->num = data;
          if (list == NULL || position <= 0) {
              temp->next = list;
              return temp;
          } else {
              node *curr = list;
              while (position-- > 0 && curr->next != NULL) {
                  curr = curr->next;
              }
              temp->next = curr->next;
              curr->next = curr;
              return list;
          }
      }
      

      【讨论】:

      • void insert ---> node *insert ;)
      • 如何从 void 函数返回 node* 或 NULL?
      • @user3283146:答案已更正。它需要进一步改进 ;-)
      猜你喜欢
      • 1970-01-01
      • 2015-06-16
      • 2015-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多