problem:
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
.
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
ListNode* result = new ListNode(0);
if(head == NULL || head->next == NULL)
return head;
int flag = 0;
int last;
ListNode* index = head;
ListNode* resultindex = new ListNode(0);
if(head->val != head->next->val)
{
result->next = index;
last = index->val;
index = index->next;
result->next->next = NULL;
resultindex = result->next;
flag++;
}
else
last = index->val;
while(index != NULL)
{
if(index->val != last)
{
ListNode* nextnode = index->next;
if(nextnode != NULL && index->val == nextnode->val)
{
last = index->val;
index = index->next;
}
else
{
if(flag == 0)
{
result->next = index;
index = index->next;
if(index != NULL)
result->next->next = NULL;
resultindex = result->next;
flag++;
}
else
{
last = index->val;
resultindex->next = index;
index = index->next;
resultindex = resultindex->next;
resultindex->next = NULL;
}
}
}
else
{
index = index->next;
}
}
return result->next;
}
};