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.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
#include <iostream>
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution
{
public:
ListNode *deleteDuplicates(ListNode *head)
{
if (head == NULL)
{
return NULL;
}
// only has a single element
if (head->next == NULL)
{
return new ListNode(head->val);
}
ListNode Header(10);
ListNode *Tail = &Header;
ListNode *Next = NULL;
bool IsDuplicates = false;
while(head->next != NULL)
{
Next = head->next;
if (head->val != Next->val)
{
if (!IsDuplicates)
{
Tail->next = new ListNode(head->val);
// update the tail
Tail = Tail->next;
}
IsDuplicates = false;
}
else
{
IsDuplicates = true;
}
head = Next;
}
if (!IsDuplicates)
{
Tail->next = new ListNode(head->val);
}
return Header.next;
}
};
LeetCode_Remove Duplicates from Sorted List II
原文:http://blog.csdn.net/sheng_ai/article/details/45050507