删除链接列表的最后一个节点 [英] Delete the last node of a linked list

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

问题描述

我正在尝试删除链表的最后一个节点,
我有链表的第一个元素。但是该功能不起作用,如果您能帮助我,我将很高兴

I am trying to delete the last Node of a linked list, I have the first element of the list. But the function does not work I would be happy if you could help me

代码-

void deleteNode(Node* firstNode)
{
    Node* currNode = firstNode;
    while (currNode->next != NULL)
    {
     currNode = currNode->next;
    }
     delete currNode->next;
     currNode->next = NULL;
 }


推荐答案

您正在删除以下内容最后一个节点,无论如何应为NULL。

You are deleting the one after the last node, which should be NULL anyways.

void deleteNode(Node* firstNode)
{
    //first check if firstNode is NULL or last node.
    if(firstNode == NULL)
        return;

    if(firstNode->next == NULL)
    {
        delete firstNode;
        firstNode = NULL;
        return;
    }

    Node* currNode = firstNode;
    while (currNode->next && currNode->next->next != NULL)
    {
        currNode = currNode->next;
    }
    delete currNode->next;
    currNode->next = NULL;
}

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

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