您的位置:首页 > 其它

使用递归来实现在循环链表里删除第一节点不是数字‘2’

2017-07-23 16:04 423 查看
之前,小标已经写了如何使用递归来实现在单链表里删除第一个节点不是数字‘2’。那现在,小编继续用C++递归来实现在循环链表里删除第一个节点,如果第一个节点不是数字‘2’, 就将它删除。

对于循环链表的实现,目前小编只知道两种方法,第一种,就是将循环链表先断开成单链表,然后再将表连接起来。第二种,就是不将循环链表断开,直接就以循环链表来实现,但是,这种情况很容易会实现死循环。 现在,小编就用第二种方法来实现这道题目。

现在,小编还是将.h 文件里一些prototype写出来。下面就是”clist.h” 文件夹里的代码

//This is the clist.h

#include<iostream>
#include<cstring>
#include<cctype>

using namespace std;

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

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

private:
node * rear;
};


现在,为了解决这道题,那就得使用wrapper functin 和 recursive function ,这些函数的prototype 必须写在 .h 文件里,那下面就是如何写prototype的代码展示。

//clist.h
#include<iostream>
#include<cstring>
#include<cctype>

using namespace std;

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

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

//这就是 wrapper function
//Remove the first node if the first node is not 2
void remove_first();
private:
//这是 recursive function
//Remove the first node if the first node is not 2
void remove_first(node *& rear);

//这是尾指针
node * rear;
};


在 .h 文件里写完prototype之后,就得在 .cpp 里来实现这两个函数。

下面就是 clist.cpp 的file

//clist.cpp

#include "clist.h"

void list::remove_first()
{
//这个是为了将指针指向第一个节点
//这样就将这个指针传给recursive function
remove_first(rear->next);
}

void list::remove_first(node *& rear)
{
//This is the base case
if(!rear)
return;
if(rear->data != 2)
{
node * temp = rear->next;
delete rear;
rear = NULL;
rear = temp;
return;
}
}


这个就是用C++递归来实现这道题的,是不是感觉用递归很简单呢!

下面是结果的截图



从结果中,可以看出,是不是已经实现这个功能呢了,是不是很神奇呢!

以后,小编还会继续用递归来实现数据结构中的某些问题,请听下回分解!

如果对诸位有所帮助,就点赞吧!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐