在linear linked list里,如何display unique data

展示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的个数也展示出来。

下面是运行结果:

是不是感觉这道题目很容易解决。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值