给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。
样例
样例 1
输入 : 1->2->3->3->4->4->5->null
输出 : 1->2->5->null
样例 2
输入 : 1->1->1->2->3->null
输出 : 2->3->null
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: head is the head of the linked list
* @return: head of the linked list
*/
ListNode * deleteDuplicates(ListNode * head) {
// write your code here
ListNode*newhead=new ListNode(0);
newhead->next=head;
ListNode*flag=newhead;
while(head)
{
int tmp=head->val;
if(head->next==NULL||head->next->val!=tmp)
{
flag->next=head;
flag=flag->next;
head=head->next;
continue;
}
while(head!=NULL&&head->val==tmp)
{
head=head->next;
}
}
flag->next=head;
return newhead->next;
}
};