C++: one pointer solution


  • 0
    A

    class Solution {
    public:
    ListNode *deleteDuplicates(ListNode *head) {
    ListNode *cur = head;
    while(cur){
    if(cur->next && cur->val == cur->next->val){
    cur->next = cur->next->next;
    }else{
    cur = cur->next;
    }
    }
    return head;
    }
    };


  • 0
    R

    Well, but you never actually delete duplicates, you only skip them, what leads to a bad memory leak.


  • 0

    @rafal2 But how could you tell that the nodes are allocated on the heap?


  • 0
    R

    @luming89 Why would anyone store nodes on stack? List is a dynamic structure and I haven't encountered a list with nodes allocated on stack. It would be quite troublesome and generally pointless. Of course I cannot tell for sure that nodes are allocated on the heap, but the task says "Remove Duplicates..." and I guess it means that they should be removed from the memory.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.