关于单链表的知识点,小编就不在这里介绍了,如果有不懂的地方,自己查资料吧!
原题目是:Copy the contents of a linear linked list Except do not copy any 2’s and place the data into an array. Return the number of items copied
感觉这次目前小编用递归的方式来解决这道题,方法不是很好,太不简洁。若小编想到简洁的方法,还是用递归方式,就会更新这种方法。(别嘲笑小编!)
下面是list.h file 展示:
//This is the list.h file
#include<iostream>
#include<cctype>
#include<cstring>
using namespace std;
struct node
{
node * next;
int data;
};
class list
{
public:
list(); //Supplied
~list(); //Supplied
void build(); //Supplied
void display(); //Supplied
//Copy the contents of a linear linked list Except do not copy any 2's and place the data into an array
//Return the number of items copied
int copy_special();
private:
//Copy the contents of a linear linked list Except do not copy any 2's and place the data into an array
//Return the number of itmes copied
int copy_special(int *& array, node * head, int index, int count);
int copy_special(node * head);
node * head;
node * tail;
};
因为题目要求是要将特殊的节点的内容输入到数组中,所以在argument list就得传进来数组。
下面是展示如何实现这三个函数的:
//This is the list.cpp file
#include "list.h"
int list::copy_special()
{
int count = copy_special(head);
int * array = new int[count];
int result = copy_special(array,head,0,count);
for(int I = 0; I < count; ++I)
{
cout<<array[I]<<" ";
}
cout<<endl;
return result;
}
int list::copy_special(int *& array, node * head, int index, int count)
{
if(!head)
return 0;
if(head->data != 2)
{
if(index < count)
{
array[index] = head->data;
}
return copy_special(array,head->next,index+1,count)+1;
}
return copy_special(array,head->next,index,count);
}
int list::copy_special(node * head)
{
if(!head)
return 0;
if(head->data != 2)
{
return copy_special(head->next) + 1;
}
return copy_special(head->next);
}
至于如何在主函数里调用这些函数,小编就不在这里展示出来了
下面是展示结果:
小编想到更好的方法,第一时间会更新内容,敬请期待吧!