以单向链接列表删除项目

时间:2013-12-16 19:01:24

标签: c++ linked-list

我需要一个函数,根据其位置从链表中搜索项目,将信息保存在变量中并删除它。例如,我想删除列表中的第五项并将其内容保存到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;
}

我是否已正确完成所有操作以及有关如何删除的建议?

3 个答案:

答案 0 :(得分:0)

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

您需要将代码修改为

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

答案 1 :(得分:0)

您需要在删除的节点之前存储节点的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;
}

答案 2 :(得分:0)

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

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;
}