使用递归来实现在ARR里如何删除每一个list的第一个节点不是数字‘2’

在之前,小编写了如何用递归来解决同一个问题在不同的数据结构里,那现在,继续写如何在ARR里做同一个问题,同样也是不能用循环来实现。

下面是“arr.h” 文件里的代码,一些代码是已经实现了,所以小编就不写出来了

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

using namespace std;

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

class table
{
    public:
        //These functions are already written
        table();
        ~table();
        void build();
        void display();

    private:
        node ** head;  //dynamically allocated array
        int size;  //the array size
};

为了实现这道题,那就得使用pointer arithmetic to access the elements of the array。就得清楚考虑prototype如何写,下面就看小编如何在.h 文件里写prototype

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

using namespace std;

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

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

        //Write the function prototype here:

        //Remove the first node if the number is not 2 in every list
        void remove_first();

    private:
        //Remove the first node if the number is not 2 in every list
        void remove_first(node * head[], int index);
        void remove_first(node *& head);

        node ** head;  //dynamically allocated array
        int size;  //the array size
};

下面,就是如何实现这些function 在 .cpp 文件夹里了。

//arr.cpp
#include "arr.h"

//Remove the first node if the number is not 2 in every list
void table::remove_first()
{
    //这个得传head指针和数组的第一个index给recursive function
    remove_first(head,0);
}

void table::remove_fist(node * head[], int index)
{
    //因为数组的size知道了
    if(index < size)
    {
        //这个是传给recursive function
        remove_first(head[index]);
        //这个是本身函数,进行index的变化
        remove_first(head,++index);
    }
}

void table::remove_first(node *& head)
{
    if(!head)
        return;
    if(head->data != 2)
    {
        node * temp = head->next;
        delete head;
        head = NULL;
        head = temp;
        return;
    }
}

是不是感觉这个做法跟单链表,循环链表和双向链表有点相似呢!就是添加了一个数组的index变换而已,剩下的几乎一模一样。

小编是在linux环境下进行编译和运行的,下面是结果的截图:
结果展示

是不是感觉很简单呢,以后小编还会继续写在不同数据结构实现某种功能的代码,请听下回分解!

为小编点赞吧!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值