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
.
pro:给排序的链表,将链表中所有有重复节点的节点都删除。
sol:跟I不同的是删除nodes have duplicate numbers,而不是只删除duplicate。
定义cur和next指针,遍历链表。定义pre指针记录链表中合法的上一个节点,我们先用cur和next指针来做跟I中相同的事情,删除duplicates,用flag记录cur是否有重复,如果有的话,最后再删除cur,没有就三个指针都往后移。看代码吧还是。
trick:我们以next与cur不相等做为查看flag是否需要删除cur的条件,因此到循环结束时仍需要再查一次,因为很可能最后一个节点也曾经重复过,需要删除。
code:
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head)
{
if(head==NULL||head->next==NULL) return head;
ListNode *pre,*cur,*next;
ListNode *root=new ListNode(0);
root->next=head;
int val=head->val;
cur=head,next=head->next;
pre=root;
bool flag;
flag=false;
while(next!=NULL)
{
if(next->val==cur->val)
{
flag=true;
cur->next=next->next;
next=next->next;
}else
{
if(flag==true)
{
flag=false;
pre->next=cur->next;
cur=next;
next=next->next;
}else
{
pre=cur;
cur=next;
next=next->next;
}
}
}
if(flag==true)
{
pre->next=cur->next;
}
return root->next;
}
};