删除链接列表中的所有节点 [英] Remove all nodes in linked list

查看:127
本文介绍了删除链接列表中的所有节点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个链接列表包含3个节点,如下图所示:

I have a linked list contains 3 nodes like the image shown:

有一个头指针,temp1指针指向列表的前面,尾点指向列表的末尾。

There is a head pointer and temp1 pointer point to the front of the list, and tail point points at the end of the list.

我要删除所有节点,并将其改回原始初始形式(tail = NULL,head = first_node,但第一个节点没有任何值在数据和下一个字段)。

I want to remove all the nodes, and change it back to its original initial form ( tail = NULL, head = first_node , but the first node doesn't have any value in the data and next field).

因为我想开始添加一些新的值。要删除所有这些数据,这个代码将删除这个链表中的节点,并留给第一个节点没有值在数据和下一个字段?

Because I want to start putting up some new values in it. To remove all those data, is this code going to remove nodes inside this linked list and left with the first node with no values in data and next field?

此代码在C ++中:

while(temp1!=tail)
{
    temp1 = temp1->next;
    if(temp1->next == tail)
    {
        tail=temp1;
        temp1 = temp1->next;
        free(temp1);    
    }
}

但是,这是否意味着只有最后一个节点被删除?有没有办法删除除第一个节点以外的所有节点?

But then, does this mean only the last node will be deleted? are there any way to delete all the nodes except the first one?

推荐答案

尝试下面的代码。

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.

这篇关于删除链接列表中的所有节点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆