Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5
, return 1->2->5
.
Given 1->1->1->2->3
, return 2->3
.
删除排序链表中所有重复的节点,删除完成后,原链表中的重复节点全部删除。
链表排序说明重复节点都处于相邻位置,遍历链表并比较当前节点是否和下一个节点重复:
如果重复:删除下一个节点,重复该操作直到下一个节点为空或者和当前节点不重复,只要执行过删除操作,就说明原链表曾经有和当前节点重复的节点,根据题目要求,此时还需要将当前节点删除掉,所以在判断下一个节点为空或者和当前节点值不同时,将当前节点删除。
如果不同:则移动到链表的下一个节点继续重复以上判断,直到链表结束。
AC code:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head)
{
if(head==NULL||head->next==NULL)
return head;
ListNode *p,*q,*pre;
ListNode *dummyHead=new ListNode(0);
dummyHead->next=head;
pre=dummyHead;
p=pre->next;
while(p!=NULL)
{
if(p->next!=NULL&&p->next->val==p->val)
{
q=p->next;
p->next=q->next;
delete q;
if(p->next==NULL||(p->next!=NULL&&p->next->val!=p->val))
{
pre->next=p->next;
delete p;
p=pre->next;
}
}
else
{
p=p->next;
pre=pre->next;
}
}
p=dummyHead->next;
delete dummyHead;
return p;
}
};
2014/8/11更新,和Remove Duplicates from Sorted List写法统一以后的程序:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head)
{
ListNode *p,*q,*pre;
ListNode *dummyHead=new ListNode(0);
dummyHead->next=head;
pre=dummyHead;
p=pre->next;
while(p!=NULL)
{
if(p->next==NULL||p->val!=p->next->val)
{
p=p->next;
pre=pre->next;
continue;
}
q=p->next; //删除重复节点
p->next=q->next;
delete q;
if(p->next==NULL||p->val!=p->next->val) //删除当前节点
{
pre->next=p->next;
delete p;
p=pre->next;
}
}
p=dummyHead->next;
delete dummyHead;
return p;
}
};