Got accepted (C++ code), any improvements?


  • 0
    A
    class Solution {
    

    public:
    ListNode *deleteDuplicates(ListNode *head) {
    if(head == NULL)
    return head;
    else{
    ListNode *p = head;

            while(p->next != NULL){
                if(p->val == p->next->val){
                    ListNode *temp = p->next;
                    p->next = temp->next;
                    delete temp;
                    p = head;
                }
                else    p = p->next;
            }
            
            return head;  
        }
    }
    

    };

    This is my version. It has been accepted. However, I want to ask 1 question:
    When I declared ListNode *p = head, I declared a pointer to the same address as head. In other words, any changes with p will affect the object *head. Is this correct? That's why I can return head in the end of the function.


  • -1
    M

    It might be redundant to use a temp var and actually call delete on the node. A simpler way is to reroute the links. For example:

    head->1->1->3 
    

    becomes

    head->1->3
          1--^
    

    See that the other 1 is not actually deleted just was rerouted over by the other one. The head will always point at the first node of the list. My code:

    struct ListNode *deleteDuplicates(struct ListNode *head) {
    	struct ListNode *p1 = head, *p2;
    
    	while (p1) {
    		p2 = p1->next;
    		while (p2 && p2->val == p1->val)
    			p2 = p2->next;
    		p1->next = p2;
    		p1 = p1->next;
    	}
    	return head;
    }
    

  • 0
    L

    I think your description "In other words, any changes with p will affect the object *head" is right.


Log in to reply
 

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