链接列表删除

时间:2013-11-10 22:31:04

标签: c++ pointers

当移动链接列表并创建一个临时指针来移动它时,我们是否必须删除tmp指针或自动删除它。我理解为分配新内存,我们需要删除为指针分配的内存,然后将指针设置为null,但如果我们只有一个指针,即

Node*follow=head; //where head is a pointer to a linked list

最后我们需要删除以下内容吗?即使它没有分配新内存,我只是用它来浏览列表?

int countNum (Node *head, int key)
{
    int count=0;

    if (head == nullptr)
        return 0;

    Node *follow=head;

    while (follow != nullptr) 
    {
        if(follow->val == key)
            count++;

        follow=follow->next;
    }

    cout << count;
    return count;
}

int main()
{
    Node *head = (1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));

    int counts=0;

    counts= countNum(head,2);

    cout<< counts<< head;
    return 0;
}

我试图对此进行编译,但它崩溃并说int count = 0;是一个线程断点?并且我的Node * head =(1,cons(2,cons(2,(cons(4,(cons(5,nullptr)))))));没有被使用..

2 个答案:

答案 0 :(得分:0)

您不需要删除“指针”(实际上不应该删除),因为删除是为分配的内存。指针只是一种引用已分配内存部分的方法。

此代码......

delete ptr;

...不会删除名为ptr的指针 - 而是删除ptr指向的已分配内存。实际上,它的效果与此代码相同:

ptr2 = ptr;
delete ptr2;

因为它再次删除了相同的分配内存,因为ptrptr2指向同一个地方。指针本身的名称/位置无关紧要;这是他们指出重要的地方。

答案 1 :(得分:0)

声明指针就像声明任何(int,double等)变量一样。删除指针时,删除指针指向的内存而不是指针本身。