83. Remove Duplicates from Sorted List

1. Description

Given a sorted linked list, delete all duplicates such that each element appear only once.

2. Example

Example 1:
Input: 1->1->2
Output: 1->2

Example 2:
Input: 1->1->2->3->3
Output: 1->2->3

3. Solutions

My Accepted Solution

n is the number of nodes in m_head
Time complexity: O(n)
Space complexity: O(1)

class Solution 
{
public:
    // ListNode* deleteDuplicates(ListNode* head)
    ListNode* deleteDuplicates(ListNode *m_head) 
    {
        if(!m_head) return nullptr;
        
        for(auto iter = m_head; iter->next; )
        {
            if(iter->val == iter->next->val)
                iter->next = iter->next->next;
            else
                iter = iter->next;
        }
        
        return m_head;
    }
};
comments powered by Disqus