c++ - 使用 `delete` 从链表中删除节点

标签 c++ pointers linked-list delete-operator

这是从单向链表的尾部删除一个元素的部分代码:

int SLList::deleteFromTail()
{
    int el = tail->info;

    //if the list has only one element
    if(head == tail) {
        delete head;
        head = tail = 0;
    }
    else {
        //some code here...
    }

    return el
}

这里的headtail分别是指向LL的第一个和最后一个元素的指针。

delete head 之后的 if block 中,我们设置 head = tail = 0

但是在我们删除了 head 之后,我们如何设置它的值呢?(在本例中为 NULL)

最佳答案

Head 是一个指针。您正在删除 pointer 指向的 object,而不是 pointer 本身

考虑这个例子:

Foo *foo = new Foo(); //foo does not store Foo object. Just an adress of created object.
//do some stuff
delete foo; //object is deleted
foo = new Foo(); //create another Foo and make foo point to it

编辑 指针只是对象的地址。当您编写 delete head 时,您删除了 head 指向的对象,但即使在删除之后 head pointer 仍将指向与之前相同的位置。但是取消引用它(例如 *head)会导致问题。

关于c++ - 使用 `delete` 从链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11361147/

相关文章:

将链表转换为队列(移动节点)

java - 如何对 LinkedList<String> 进行排序?

c++ - 将持续时间值设为双倍

C malloc 指向 NULL 的指针不起作用

c - 在 C 中使用 malloc 动态创建一个二维指针数组

c - 如何连接结构节点(链表)?

java - 如何实现使用模板的界面?

c++ - 在 C++ 中生成一个字符串映射到 std::list of pointers

c++ - 为什么 c++ 不包括\n 而 python 不是

c++ - 如何在 void 函数内正确动态分配二维数组?