您的位置:首页 > 编程语言 > C语言/C++

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

2017-10-25 11:34 561 查看
这道题目是小编考期中的题目,当时再做的时候,尽然忘记了一个条件,最后跑出无限循环。哎!可惜了。

不说了,直接上代码:

//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;
}
}


下面是结果的展示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: