/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::deleteDuplicates(ListNode* A)
{
if(A == NULL)
return A;
ListNode *curr, *itr; // create two pointers for current position and next postion
curr = A;
itr = curr->next; // initialize them
while(curr->next != NULL) // while the iterator doesn't reach the end
{
if(curr->val == itr->val)
{
itr = itr->next; // if values are same, keep increasing the window
if(itr == NULL) // if the last two elemets are same
{
curr->next = itr; // set the current to itr and break out
}
}
else
{
curr->next = itr; // connect the unique elements dropping the repeated element
curr = itr; // update current to the next unique number
itr = itr->next; // increment the iterator
}
}
return A; // return the head
}
Very readable solution: Running time O(n), Memory O(1)
porygon-Z
#1