Display the linear linked list by traversing reverse

题目的意思就是要将单链表的节点内容以从尾到头的方式进行展示出来。
下面是代码的展示:

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

using namespace std;

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

class list
{
    public:
            //These function are already written for you
            list();  //Supplied
            ~list();  //Supplied
            void build();  //Supplied
            void display(); //Supplied

            //Display the node by reversing
            void display_reverse();

    private:
            //Display the node by reversing
            void display_reverse(node * head);

            node * head;
            node * tail;

};

虽然,class里面有tail 指针,但是不能用tail来display data 出来,因为这是单链表,不是双链表。

下面是展示如何来实现这两个函数的,就得用到尾递归

#include "list.h"

void list::display_reverse()
{
    display_reverse(head);
}

void list::display_reverse(node * head)
{
    if(!head)
        return;
    //这一步是将head指针直接指向
    display_reverse(head->next);
    cout<<head->data<<" ";
    return;
}

如何在主函数里调用函数,那我就不在这里展示了,下面是展示结果:

这个就是递归的方法来实现这个功能的。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值