Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

单链表删除某个节点之后,这个节点还存在 #513

Open
yangxin6 opened this issue Jul 15, 2021 · 1 comment
Open

单链表删除某个节点之后,这个节点还存在 #513

yangxin6 opened this issue Jul 15, 2021 · 1 comment

Comments

@yangxin6
Copy link

大佬,问下我创建完一个单链表之后,删除一个节点,但是该节点还存在在内存中,不知道为啥
下面是我的代码

// 单链表节点
struct listNode {
    int value;
    struct listNode *next;
};
// 带头节点的单链表 长度len记录在头结点的value中
listNode *linkedListCreate(int len) {
    listNode *head = new listNode{len, nullptr};
    listNode *p = head;
    for (int i = 1; i <= len; ++i) {
        p->next = new listNode{i, nullptr};
        p = p->next;
    }
    return head;
}
// 删除(删除要先找到该节点的前前驱结点, 不能删除头结点)
void del(listNode *head, listNode *elem) {
    if (!elem || !head)
        return;
    listNode *pre = head->next;
    while (pre->next->value != elem->value) {
        pre = pre->next;
    }
    pre->next = elem->next;
    elem->next = nullptr;
    head->value--;
    delete elem;
}
// 找到 value 的节点,并返回对应节点的地址
listNode *find(listNode *head, int value) {
    listNode *p = head->next;
    while (p) {
        if (p->value == value)
            break;
        p = p->next;
    }
    if (p == nullptr) {
        std::cout << "改节点不存在与链表中" << std::endl;
        return nullptr;
    }
    return p;
}
int main() {
// 创建链表
    listNode *list = linkedListCreate(6);
// 删除
    listNode *node3 = find(list, 3);
    del(list, node3);
    std::cout << "地址:" << node3 << " value:" << node3->value << std::endl;
    // 打印结果: 地址:0x7fe9b5604740 value:3
    return 0;
}
@OrangeTien
Copy link

动态分配的那个地址确实是被删除了的,这个del()函数并没有什么问题。我想之所以你会这么问,是因为你观察的指向node的指针的值并没有任何的变化,原因是这样:我们删除了那块地址(也就是那块地址被释放),但是原本指向那块地址的指针的值我们没有去改变它,即使那个地址已经并不是一块符合链表节点格式的空间。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants