正在删除单向链表中的项目

Deleting item in one way linked list

本文关键字:项目 链表 删除      更新时间:2023-10-16

我需要一个函数,该函数根据链接列表中的项目的位置从链接列表中搜索该项目,将信息保存在变量中并删除它。例如,我想删除列表中的第五个项目,并将其内容保存到int&数字和字符串&文本"我的列表"仅在一个方向上链接。我想我已经找到了,但移除它有点困难。

private:
    struct List_cell{
        unsigned number;
        string text;
        List_cell *next;
    };
    List_cell *list_first_;

bool LinkedList::find_and_remove(unsigned& position, unsigned& count, unsigned& found_number, string& found_text){
List_cell *current = list_first_;
if(current == nullptr){
    return false;
}
else{
    while(current != nullptr){
        count++;
        current = current->next;
        if(count == position){
            found_number = current->number;
            found_text = current->text;
                            //here should be the deleting i think
            return true;
        }
    }
}
return false;
}

我做的每件事都正确吗?如何删除有什么建议吗?

编程引理:所有问题都可以通过额外的间接层来解决:

bool LinkedList::find_and_remove( unsigned& position,
                                  unsigned& count,
                                  unsigned& found_number,
                                  string& found_text )
{
    List_cell **work = &list_first_;
    while(*work != nullptr) {
        if ( ++count == position ) {
            List_cell *tmp = *work;
            *work = (*work)->next;
            found_number = tmp->number;
            found_test = tmp->text;
            delete tmp;
            return true;
        }
        work = &(*work)->next;
    }
    return false;
}

您已经找到要删除的节点,所以现在您只需要将之前的节点链接到之后的节点。因此,您需要一个指向该节点之前节点的指针。

您需要将代码修改为

if head is null, return false
initialize counter to 0
create two pointers: p as head and q as head->next
while q != null do
    if counter == position do <- q is pointing to the node you need to remove
        store the info from q
        p->next = q->next <- this is where the node gets removed
        return true
    q = q->next
    p = p->next
return false

或者递归:(不总是建议,但需要更少的代码)

deleteNode(head, position):
    if head == null 
        return null
    if position == 0:
        return head->next
    head->next = deleteNode(head->next, position - 1)
    return head

您需要将节点的next指针存储在已删除节点之前,并将其附加到已删除单元格之后的节点。

所以你需要一个以前的指针

List_cell* previous;

在你的while循环

count++;
previous = current;
current = current->next;
if(count == position){
    found_number = current->number;
    found_text = current->text;
    previous->next = current->next;
    delete current;
    return true;
}