在之前,小编写了如何用递归来解决同一个问题在不同的数据结构里,那现在,继续写如何在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环境下进行编译和运行的,下面是结果的截图:
是不是感觉很简单呢,以后小编还会继续写在不同数据结构实现某种功能的代码,请听下回分解!
为小编点赞吧!!