【问题标题】:Delete a node from a given position in linked list [closed]从链表中的给定位置删除节点[关闭]
【发布时间】:2016-04-14 11:09:21
【问题描述】:

我想从列表中的给定位置删除一个节点, 但我的删除功能不起作用。 请帮帮我。

提前致谢。

Node* Delete(Node *head, int position)
{
  int count=0;
  Node* temp, *temp1, *temp2;
  temp = head  ;
if(head==NULL){
    return 0;
    }
else if(position == 0)
    {

    head = head->next;
    free(temp);
    return head;
}
  else{
      while(count!= position-1)
         {
         temp = temp->next;
         count++;   
     }
     temp1 = temp->next;
     temp->next = temp1->next;

     free(temp1);
     return temp;
 }

return head;
}

【问题讨论】:

  • 如何它不起作用?你有构建错误吗?崩溃?您是否尝试过在调试器中运行?逐行遍历代码,看看哪里出错了?
  • 请定义所需的行为。返回值应该是多少?
  • 我的猜测:return temp; 应该被删除。
  • 非常感谢 MikeCAT...我从代码中删除了“return temp;”...现在它工作正常...:)

标签: c data-structures linked-list


【解决方案1】:

首先,正确格式化您的代码。

然后,删除return temp;,这样前一部分列表就不会丢失了。

您也可以先删除return head;,因为该函数无论如何都会在最后一部分执行return head;

Node* Delete(Node *head, int position)
{
  int count=0;
  Node *temp, *temp1, *temp2;
  temp = head;
  if(head==NULL){
    return NULL;
  }
  else if(position == 0)
  {
    head = head->next;
    free(temp);
  }
  else{
    while(count!= position-1)
    {
      temp = temp->next;
      count++;
    }
    temp1 = temp->next;
    temp->next = temp1->next;

    free(temp1);
  }

  return head;
}

请注意return 0; 是有效的,因为0 是一个空指针常量(N1256 6.3.2.3 指针)并且定义了将其转换为指针,但使用NULL 更好,因为它会更清楚它正在处理一个指针。

【讨论】:

    【解决方案2】:

    return temp; 替换为return head; 还包括如果有节点少于位置的处理逻辑。

    【讨论】:

      【解决方案3】:

      我只想补充 MikeCAT 的答案。当节点数小于位置时,您还应该处理这种情况。

      其中一种方法可能是:

      while(count!= position-1) { temp = temp->next; if(temp == NULL) return head; count++; }

      【讨论】:

        【解决方案4】:

        删除return temp 并写入return head。 此外,检查位置是否大于链表中的节点数。 同样在释放指针之前,我建议添加temp1->next=NULL,然后添加free(temp1)

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-01-11
          • 1970-01-01
          相关资源
          最近更新 更多