给定一个排序链表,删除所有重复的元素只留下原链表中没有重复的元素。
样例
样例 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
if(head == NULL)
return head;
ListNode* ret = NULL;
ListNode* tail = NULL;
ListNode* pre = head;
head = head->next;
int count = 1;
while(head)
{
ListNode* next = head->next;
if(head->val == pre->val)
{
count++;
}
else
{
if(count == 1)
{
if(ret == NULL)
{
ret = pre;
tail = pre;
tail->next = NULL;
}
else
{
tail->next = pre;
tail = pre;
tail->next = NULL;
}
}
else
{
}
count = 1;
pre = head;
}
if(next == NULL)
{
if(count == 1)
{
if(ret == NULL)
{
ret = pre;
tail = pre;
tail->next = NULL;
}
else
{
tail->next = pre;
tail = pre;
tail->next = NULL;
}
}
}
head = next;
}
cout<<count<<endl;
return ret;
}
};