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

来源:互联网 发布:java随机生成汉字名字 编辑:程序博客网 时间:2024/06/14 00:58

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

不说了,直接上代码:

//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
原创粉丝点击