这道题目是小编考期中的题目,当时再做的时候,尽然忘记了一个条件,最后跑出无限循环。哎!可惜了。
不说了,直接上代码:
//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;
}
}
下面是结果的展示: