leetcode Quesion 79: Remove Duplicates from Sorted List

Remove Duplicates from Sorted List

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Analysis:
This problem is a classic one using the pointers.
Idea is just link the duplicates to the next element.

e.g.            1->1->1->2->3->4
1st step      1 ----->1->2->3->4
2nd step     1 --------->2->3->4


Code:

/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (head==NULL){return NULL;}
        if (head->next==NULL){return head;}
        ListNode* list = head;
        while (head->next!=NULL){
            
            if (head->next->val==head->val){
                head->next=head->next->next;
            }else{
                head = head->next;
            }
        }
        return list;
    }
};

1 comment:

  1. will the solution have memory leak at
    if (head->next->val==head->val){
    head->next=head->next->next;
    }?
    Should this be:

    if (head->next->val==head->val){
    ListNode *temp = head->next;
    head->next=head->next->next;
    delete temp;
    }?

    Thanks.

    ReplyDelete