如何remove the last node in LLL

本文介绍了一种使用递归方法在单链表中删除最后一个节点的技术,并提供了详细的C++实现代码。通过修改头节点和尾节点指针,确保链表结构的正确更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目的意思就是,在单链表里,如何用递归来将最后一个节点删除掉。

下面是代码展示:

//This is the list.h file
#include<iostream>
#include<cstring>
#include<cctype>

using namespace std;

struct node
{
    int data;
    node * next;
};

class list
{
    public:
        //These functions are already written for you
        list();  //supplied
        ~list(); //supplied
        void build(); //supplied
        void dispaly(); //supplied

        //Remove the end of the LLL
        //Return the last node to the main function
        int remove_end();
    private:
        //Remove the end of the LLL
        //Return the last node to the main function
        int remove_end(node *& head, node *& tail);

        node * head;
        node * tail;
};

因为,建立的链表用到tail指针,所以在删除最后一个节点的时候,那么就得将pass by reference of the tail pointer and the head pointer。

下面展示,如何来实现这两个函数的代码:

#include "list.h"

int list::remove_end()
{
    return remove_end(head,tail);
}

int list::remove_end(node *& head, node *& tail)
{
    if(!head)
    {
        int num = head->data;
        delete head;
        head = NULL;
        return num;
    }
    if(!head->next->next)
    {
        int num = head->next->data;
        delete head->next;
        head->next = NULL;
        tail = head;
        return num;
    }
    return remove_end(head->next,tail);
}

小编在这里就不写如何在主函数里调用来运行了
下面就展示结果:

从结果中可以看出,已经将原先的list的最后一个节点(也就是数字’2’)删除,那么返回的就是之前最后一个节点。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值