给定一个无序单链表的头节点 head,删除其中值重复出现的节点。
例如:1->2->3->3->4->4->2->1->NULL,删除值重复的节点之后为1->2->3->4->NULL。
循环遍历,类似于选择排序思想
#include <iostream>
using namespace std;
//结点
struct Node
{
int value;
Node* next;
};
//尾插法
Node* create_list(int v, int len)
{
Node* ret = NULL;
Node* slider = NULL;
for(int i=0; i<len; i++)
{
Node* n = new Node();
n->value = v++;//头结点
n->next = NULL;
if(slider == NULL)
{
slider = n;//slider和头结点挂接
ret = n;//ret指向头结点
}
else
{
slider->next = n; //尾插法
slider = n;//移动slider指向新插入的结点
}
}
Node* n1 = new Node();
n1->value = --v;
n1->next = NULL;
slider->next = n1;
return ret;//返回链表头结点
}
void destory_list(Node* list)
{
while(list)
{
Node* del = list;
list = list->next;
delete del;
}
}
void print_list(Node* list)
{
while(list)
{
cout << list->value << "->";
list = list->next;
}
cout << "NULL" << endl;
}
void removeNode(Node* list)
{
Node* cur = list;
Node* pre = NULL;
Node* next = NULL;
while(NULL != cur)
{
pre = cur;
next = cur->next;
while(NULL != next)
{
if(cur->value == next->value)
{
pre->next = next->next;
}
else
{
pre = next;
}
next = pre->next;
}
cur = cur->next;
}
}
int main()
{
Node* list = create_list(1, 5);
print_list(list);
removeNode(list);
print_list(list);
return 0;
}