您的位置:首页 > 其它

Display the linear linked list by traversing reverse

2017-10-23 13:27 429 查看
题目的意思就是要将单链表的节点内容以从尾到头的方式进行展示出来。

下面是代码的展示:

//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;
}


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



这个就是递归的方法来实现这个功能的。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: