题目
给定排序的链表,删除重复元素,只保留重复元素第一次出现的结点。
如:
给定:2->3->3->5->7->8->8->8->9->9-10
返回:2->3->5->7->8->9-10
解析
代码如下:若p->next的值和p的值相等,则将p->next->next赋值给p,删除p->next;重复上述过程,直至链表尾端。
// suanfa1.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <stdlib.h>
typedef struct tagSNode
{
int value;
tagSNode* pNext;
tagSNode(int v): value(v), pNext(NULL){}
}SNode;
void Print(SNode* pHead)
{
if (!pHead)
{
return;
}
SNode* p = pHead->pNext;
while(p)
{
printf("%d ", p->value);
p = p->pNext;
}
printf("\n");
}
void DeleteDuplicateNode(SNode* pHead)
{
SNode* pPre = pHead->pNext;
SNode* pCur;
while (pPre)
{
pCur = pPre->pNext;
if (pCur && (pCur->value == pPre->value))
{
pPre->pNext = pCur->pNext;
delete pCur;
}
else
{
pPre = pCur;
}
}
}
void Destory(SNode* pHead)
{
SNode* next;
while (pHead)
{
next = pHead->pNext;
delete pHead;
pHead = next;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
SNode* pHead = new SNode(0);
int data[] = { 2, 3, 3, 5, 7, 8, 8, 8, 9, 9, 30};
int size = sizeof(data) / sizeof(int);
for (int i = size - 1; i >= 0; i--)
{
SNode* p = new SNode(data[i]);
p->pNext = pHead->pNext;
pHead->pNext = p;
}
Print(pHead);
DeleteDuplicateNode(pHead);
Print(pHead);
Destory(pHead);
system("pause");
return 0;
}
还有一个版本去重是将有重复的都删除掉,不做解释了,无序的先自己排序然后进行去重