【问题标题】:why i cannot delete my node with reference为什么我不能参考删除我的节点
【发布时间】:2012-12-06 21:12:47
【问题描述】:
void deleteElement(LinkedListElement<char> *&pending)
{
    if (pending->Next) {
        char value = pending->Next->Data;
        pending->Data = value;
        LinkedListElement<char> *temp = pending->Next;
        pending->Next = pending->Next->Next;
        delete temp;
    }else{
        delete pending;
        pending = NULL;
    }
}

LinkedListElement<char> *l1 = new LinkedListElement<char>('a');
LinkedListElement<char> *l2 = new LinkedListElement<char>('b');
LinkedListElement<char> *l3 = new LinkedListElement<char>('a');
LinkedListElement<char> *l4 = new LinkedListElement<char>('c');
l1->setNext(l2); l2->setNext(l3); l3->setNext(l4);

printLinkedList(l1);
deleteElement(l4);
printLinkedList(l1);

我想问的是在 else 语句中的简单棘手的删除节点,如果链表是 end ,那么我可以删除 end 本身。

但是两个打印函数,总是打印abac,第二个方式是abac。 因为我只是通过引用传递参数,(&),我想如果我想删除l4 我不需要更改l3->Next,因为我可以将l4更改为NULL,而l3->Next将为NULL。

我尝试使用

delete pending; pending=NULL;

为什么不起作用,两个打印功能总是打印abac

【问题讨论】:

  • 我真的很喜欢你的标题。
  • 发生了什么让您相信自己做不到?
  • 您应该尝试解释您的实际问题是什么,它是编译问题,运行时?正如克里斯所说 - 会发生什么
  • 我改了,你能再看看吗!

标签: c++


【解决方案1】:

delete l4,但你从未更改l3,它指向l4s 内存(现已删除),其中仍包含数据('c')

你需要

l3->setNext(NULL);

从列表中删除元素(当然你仍然必须删除它)

要使用deleteElement 函数,您需要将其更改为遍历列表(伪代码):

void deleteElement( Element head , Element toBeDeleted)
{
    //are we deleting head (the first element of the list?) 
    //yes then head should be nulled, and delete as normal

    current = head ; ancestor = head;

    //scan through list (current becomes current->next until no more)
    //until we find toBeDeleted
    //maintain ancestor as we go 

    //if found set ancestor->next to current->next
    //delete toBeDeleted
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-23
    • 1970-01-01
    • 2021-09-15
    相关资源
    最近更新 更多