使用递归来实现在ARR里如何删除每一个list的第一个节点不是数字‘2’
来源:互联网 发布:spring aop 面试 知乎 编辑:程序博客网 时间:2024/06/02 03:11
在之前,小编写了如何用递归来解决同一个问题在不同的数据结构里,那现在,继续写如何在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 listvoid 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环境下进行编译和运行的,下面是结果的截图:
是不是感觉很简单呢,以后小编还会继续写在不同数据结构实现某种功能的代码,请听下回分解!
为小编点赞吧!!
阅读全文
1 0
- 使用递归来实现在ARR里如何删除每一个list的第一个节点不是数字‘2’
- 使用递归来实现在循环链表里删除第一节点不是数字‘2’
- 使用递归来解决在单链表里删除第一节点不是数字‘2’
- 使用递归来实现双向链表里删除第一节点不是数字‘2’
- 使用递归来实现删除单链表中最后一个节点不是数字‘2’
- 如何使用C++递归来实现在BST(Binary Search Tree)里将所有的叶子节点上的数字求和
- 如何在第二个程序中把第一个程序的dataset里的内容调出来
- [VB.NET]如何在第二个窗体里使用第一个窗体的控件方法
- 如何使用javascript将一段文字中的每一个单词的第一个字母转换为大写
- zTree实现获取当前选中的第一个节点在同级节点中的序号
- 如何用C++递归来删除所有的BST节点
- 使用Starling框架在Flash Builder里搭建第一个GPU加速的2D项目
- 如何遍历JTree的每一个节点?
- 如何在遍历中使用list的删除函数
- 获取一个字符串里的第一个数字的位置
- 删除链表第一个给定的节点
- 单链表实现大于第一个元素的节点在后,小于第一个节点的元素在前
- 如何使用C++递归来删除单链表中某一个由用户输入特定的值
- ubuntu 安装ORACLE JDK失败后导致的系统错误及UPDATE错误的解决办法
- Rosalind-查找motif位置
- GitHub
- 关键时刻不纠结的秘密:极简选择
- C语言单链表的创建和简单使用
- 使用递归来实现在ARR里如何删除每一个list的第一个节点不是数字‘2’
- RequestMappingHandlerAdapter源码讲解
- IntelliJ Idea 2017 免费激活方法
- 设计模式-创建型模式总结
- 异或 ^ 的几个作用
- ssh连接提示 "Connection closed by remote host"
- C++之将成员变量声明为private(22)---《Effective C++》
- unity的学习----NavMeshAgent,自动寻路
- 使用递归来实现删除单链表中最后一个节点不是数字‘2’