展示unique data就是将没有重复过的数字展示出来,至于linear linked list的翻译就是单链表,关于单链表的知识点,小编就不在此介绍了。
下面就直接上代码:
//This is the list.h
#include<iostream>
#include<cstring>
#include<cctype>
using namespace std;
struct node
{
int data;
node * next;
};
class list
{
public:
//These functions are already written for you
list(); //supplied
~list(); //supplied
void build(); //supplied
void display(); //supplied
//Display the unique data in the LLL
int display_unique();
private:
//Display the unique data in the LLL
int display_unique(node * head,node * current);
int compare(node * head, int num);
node * head;
node * tail;
};
有可能大家对在private里的function prototype不习惯,那我先介绍专门用递归来解决的函数,
int display_unique(node * head, node * current);
这个函数的argument list 里有两个参数,第一个参数是专门指向第一个节点,而current指针是专门用来遍历整个链表的。
int compare(node * head, int num);
这个函数的第一个argument是专门指向第一个节点,num这个参数是代表当前所指的节点的内容是什么。
下面是展示如何来实现这三个函数的:
//This is the list.cpp
#include "list.h"
//Display the unique data in the LLL
int list::display_unique()
{
return display_unique(head,head);
}
int list::display_unique(node * head, node * current)
{
if(!head || !current)
return 0;
if(compare(head,current->data) == 1)
{
cout<<current->data<<" ";
return display_unique(head,current->next) + 1;
}
}
int list::compare(node * head, int num)
{
if(!head)
return 0;
if(head->data == num)
return compare(head->next,num) + 1;
return compare(head->next,num);
}
稍微解释一下,第一个函数是wrapper function, 剩下的函数都是recursive function,当wrapper function传参给第二个recursive function的时候,就得需要将head指针传给recursive function,那么函数再跑的时候,就会从第一个节点开始。
我就不写在主函数里如何调用这些函数了
然后展示的结果就是将所有的unique data展示出来,并且将unique data的个数也展示出来。
下面是运行结果:
是不是感觉这道题目很容易解决。