微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

单链表中删除节点的指针

如何解决单链表中删除节点的指针

代替*head_ref = temp->next;,为什么我不能将其指定为*head_ref = *head_ref->next

我为什么要使用 temp?他们不是指向同一个地方吗?

class Node{
public:
    int data;
    Node* next;
};

void deleteNode(Node** head_ref,int key){
    Node* temp = *head_ref;
    Node* prev = NULL;
    
    if(temp!=NULL && temp->data==key){
        *head_ref = temp->next;
        delete temp;
        return;
    }
    
    else{
        while(temp!=NULL && *head_ref->data!=key){
            prev = temp;
            temp = temp->next;
        }
    }
    

解决方法

您的代码无法编译,*head_ref->data 应该是 (*head_ref)->data

你应该使用temp的原因是你想修改*head_ref,只有当你要删除的元素是head元素时。如果删除列表中的任何其他元素,则头指针必须保持不变。

但无论如何你的代码是错误的。你正在以错误的顺序做事。必须先找到要删除的元素,然后再处理删除。

您的代码首先处理删除,然后找到要删除的元素,这是荒谬的。

你想要这个:

void deleteNode(Node** head_ref,int key) {
  Node* current = *head_ref;
  Node* previous = NULL;

  // find element to delete
  while (current && current->data != key)
  {
    previous = current;
    current = current->next;
  }

  // if current is NULL here then the element has not been found

  if (current != NULL)
  {
    // element found,// current points to element found
    // previous points to previous element or NULL if current is head

    if (previous == NULL)
    {
      // deleting head element -> we need to update head_ref
      *head_ref = current->next;
    }
    else
    {
      // deleting any other element -> update next pointer of previous element
      previous->next = current->next;
    }

    delete current;
  }
}

话虽如此,这更像是 C 代码而不是 C++ 代码。您应该使用标准容器而不是自己制作,或者至少使用 C++ 惯用语,例如构造函数。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。