题目描述
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
1 递归
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead==NULL || pHead->next==NULL) return pHead;
while(pHead!=NULL && pHead->next!=NULL && pHead->val==pHead->next->val)
{
while(pHead!=NULL &&pHead->next!=NULL && pHead->val==pHead->next->val) {
pHead=pHead->next;
}
pHead=pHead->next;
}
if(pHead!=NULL) {
pHead->next=deleteDuplication(pHead->next);
}
return pHead;
}
};
2.
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead == NULL || pHead->next==NULL) return pHead;
ListNode *HeadNode = new ListNode(-1);
HeadNode ->next = pHead;
ListNode *pveNode = HeadNode;
ListNode *p = HeadNode->next;
ListNode *nextNode = p->next;
while(p!=NULL && p->next!=NULL){
if(p->val == nextNode->val){
while(nextNode->next != NULL && nextNode->val == nextNode->next->val){
nextNode = nextNode->next;
}
p=nextNode->next;
nextNode = p->next;
pveNode->next = p;
}else{
pveNode = p;
p=nextNode;
nextNode = nextNode->next;
}
}
return HeadNode->next;
}
};
思路3:

1.加一个头结点
2.两个临时指针p,q
3.找前后不相等的节点
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if (pHead == NULL || pHead->next == NULL)
return pHead;
/*---------先为链表创建一个头结点---------*/
int firstNumber = pHead->val;
//假设我的头结点数值为-1
int myFirst = -1;
//万一链表的头结点也为-1,那么我就改成-2
if (myFirst == firstNumber)
{
myFirst = -2;
}
ListNode *head = new ListNode(myFirst);
head->next = NULL;
head->next = pHead;
ListNode *p = head;
ListNode *q = head->next;
while (q)
{
while (q->next && (q->next->val == q->val))
{
q = q->next;
}
if (p->next != q)
{
q = q->next;
p->next = q;
}
else
{
p = q;
q = q->next;
}
}
//返回的时候,注意去掉头结点(自己创建的辅助节点)
return head->next;
}
};