Remove Duplicates from Sorted List II
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) {}
* };
*/
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
//if(head == NULL || head->next == NULL)
// return head;
ListNode* start = head;
ListNode* startParent = NULL;
ListNode* curr = head;
while(curr!=NULL)
{
if(curr->next == NULL)//
{
if(start != curr)
{
if(startParent == NULL)//删除的是头结点
head = curr->next;
else
startParent->next = curr->next;
}
break;
}
if(curr->next->val == curr->val)//如果相等,则判断相等的数据有多少
curr = curr->next;
else
{
//delete nodes from start to end
if(start!=curr)
{
if(startParent == NULL)//删除的是头结点
{
head = curr->next;
startParent = NULL;
}
else
{
startParent->next = curr->next;
//startParent = curr; //注意此时不要改变startParent的取值。
}
}
else
startParent = curr;
curr = curr->next;
start = curr;
}
}
return head;
}
};