我们知道C++的set底层是一颗红黑树,之前有写过红黑树的代码,知道它的机制是插入元素如果碰见相同的元素,直接插入失败,返回false,所以我们可以利用这个机制.
set的带有一个键参数的insert版本函数返回pair类型对象,该对象包含一个迭代器和一个bool值,迭代器指向拥有该键的元素,而bool值表明是否添加了元素。
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
typedef struct ListNode
{
int data;
struct ListNode *next;
}linklist;
linklist *head = NULL;
linklist *CreateList(int *arr, int len)
{
linklist* p, *rear;
head = (linklist*)malloc(sizeof(linklist));
head->data = arr[0];
rear = head;
int count = 1;
while (count < len )
{
p = (linklist*)malloc(sizeof(linklist));
p->data = arr[count];
rear->next = p;
rear = p;
count++;
}
rear->next = NULL;
return head;
}
int main()
{
int array[] = { 1,2,8,2,3,4,5};
linklist *head = CreateList(array, 7);
//定义一个新链表
linklist *NewHead,*temp;
NewHead = temp = head;
set<int> sint;
size_t len = sizeof(array) / sizeof(int);
head = head->next;
while(head)
{
//元素不重复,返回true,则结点放入temp中,并继续遍历head,否则返回false并继续遍历head
if (sint.insert(head->data).second)
{
temp->next = head;
temp = head;
head = head->next;
}
else
head = head->next;
}
temp->next = NULL;
while(NewHead)
{
printf("%d ", NewHead->data);
NewHead = NewHead->next;
}
return 0;
}