Remove all nodes in linked list

佐手、 提交于 2019-12-02 09:46:24

To delete all nodes except the first node, you can try below code.

temp1 = head->next;
while(temp1!=NULL) // as I am considering tail->next = NULL
{   
    head->next = temp1->next;
    temp1->next = NULL;
    free(temp1);
    temp1 = head->next;
}

This will delete all nodes except first one. But the data with the first node will remain as it is.

Disclaimer: I assume it's only for learning purposes and in real-world scenario you would use std::list<> or similar container.

For single-linked list, you can just drop all this burden an let the stdlib manage the pointers:

class Node {
    std::unique_ptr<Node> next;
};

You can safely use .reset() method to make operations on the list:

Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order:

  • Saves a copy of the current pointer old_ptr = current_ptr
  • Overwrites the current pointer with the argument current_ptr = ptr
  • If the old pointer was non-empty, deletes the previously managed object if(old_ptr != nullptr) get_deleter()(old_ptr).

From http://en.cppreference.com/w/cpp/memory/unique_ptr/reset.

And that's pretty much what you would do when deleting. I believe you can also use unique_ptr::swap(), to easily manipulate your nodes.

Instead of free, C++ uses delete function.

Check the link to have deep knowledge about all kind of operations(including recursive or iterative delete) on linked lists.

user2069996
temp1 = head->next;

while(temp1!=NULL) // as I am considering tail->next = NULL
{
    head->next = temp1->next;
    temp1->next = NULL;
    free(temp1);
    temp1 = head->next;
}

The logic for this would be more correct if it is this way.

After the statement

free(temp1);

Add the condition

if (head -> next != NULL)
    temp1 = head->next;

Since after deleting the last node there is no point in reassigning the address of head pointer to temp1.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!