如何用C++递归的方法来将循环链表的unique data找出来

这道题目是小编考期中的题目,当时再做的时候,尽然忘记了一个条件,最后跑出无限循环。哎!可惜了。

不说了,直接上代码:

//This is the list.h file

#include<iostream>
#include<cctype>
#include<cstring>

using namepace std;

struct node
{
    int data;
    node * next;
};

class list
{
    public:
        //These functions are provided 
        list(); //Supplied
        ~list(); //Supplied
        void build(); //Supplied
        void display(); //Supplied

        //Display the unique data in the CLL
        //Return number of unique data
        int count_unique();

    private:
        //Display the unique data in the CLL
        //Return number of unique data
        int count_unique(node * rear, node * head);
        int compare(node * head, int num);

        node * rear;
};

下面是实现这几个函数代码展示:

//This is the clist.cpp

#include "clist.h"

int list::count_unique()
{
    return count_unique(rear,rear->next);
}

int list::count_unique(node * rear, node * head)
{
    if(!head || !rear)
        return 0;
    if(head != rear)
    {
        if(compare(rear->next,head->data) == 1)
        {
            cout<<head->data<<" ";
            return count_unique(rear,head->next) + 1;
        }
        else
        {
            return count_unique(rear,head->next);
        }
    }
    else
    {
        if(compare(rear->next,head->data) == 1)
        {
            cout<<head->data<<" ";
            return 1;
        }
        else
            return 0;
    }
}

//因为这个是循环链表
//所以在找unique的时候,就得考虑到如何防止无限循环
int list::count_unique(node * head, int num)
{
    if(!head)
        return 0;
    if(head != rear)
    {
        if(head->data == num)
            return compare(head->next,num) + 1;
        else
            return compare(head->next,num);
    }
    else
    {
        if(head->data == num)
            return 1;
        else
            return 0;
    }
}

下面是结果的展示:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值