简体   繁体   English

从单个排序的链表中删除元素C ++

[英]remove an element from a singly sorted linked list C++

I have a sorted linked list and im trying to create a function to delete whatever the user passes to nameToSearch. 我有一个排序的链表,我试图创建一个函数来删除用户传递给nameToSearch的所有内容。 but i keep geting an error. 但是我一直出错。 Below is what i have so far 以下是我到目前为止所拥有的

void deleteProduct(NodePtr head, char* nameToSearch)
    {
        NodePtr nodeUnderEdit = findNodeByName(head, nameToSearch);
        if (nodeUnderEdit == NULL) 
        {
            cout<<"\n ERROR: Product not found \n";
        }
        else
        {

            delete nodeUnderEdit;
            nodeUnderEdit = nodeUnderEdit->next;

        }   

    }
  delete nodeUnderEdit;
  nodeUnderEdit = nodeUnderEdit->next;

If you delete nodeUnderEdit first, then nodeUnderEdit->next will be lost. 如果先删除nodeUnderEdit ,则nodeUnderEdit->next将丢失。 You need to first make sure that the node that before nodeUnderEdit's next is connected to nodeUnderEdit->next , then you can do the remove. 您首先需要确保nodeUnderEdit的下一个节点之前的节点已连接到nodeUnderEdit->next ,然后可以进行删除。

This is always a problem with a singly-linked list. 单链列表始终是一个问题。

The problem arises because deleting the current node from a linked list requires modifying the pointer in the previous node -- to which you don't have direct access. 出现问题是因为从链接列表中删除当前节点需要修改前一个节点中的指针-您无法直接访问该节点。

One way to handle this is to use a list with a sentinel (a final node containing a value you recognize as the end of the list). 处理此问题的一种方法是使用带有标记的列表(包含识别为列表结尾的值的最终节点)。 In this case, you can copy the value from the next node into the current node, then delete the next node from the list. 在这种情况下,您可以将值从下一个节点复制到当前节点,然后从列表中删除下一个节点。

To remove an item in a singly linked list you must change the pointer from the Previous record to point to the Next record. 要删除单链列表中的项目,必须将指针从“上一个”记录更改为指向“下一个”记录。 It is not sufficient for your "findNodeByName" to just find the node with the matching name. 仅让“ findNodeByName”查找具有匹配名称的节点是不够的。 It must find the node Previous to it in the sort order, then set the Next pointer of that record of the Next point of the record to be deleted. 它必须按排序顺序找到它的上一个节点,然后将要删除的记录的下一个点的该记录的下一个指针设置为。 Only after you have updated the Next pointer of the Previous record can you delete the record you searched for. 只有更新了上一个记录的下一个指针后,才能删除搜索的记录。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM