My Solution in C ( no no special treatment when head is null )


  • 0
    F

    If you implement this in C, you can actually drop the part that deals with the case when removing the head of the linked list is needed. The idea is to use the pointer of pointer. If we have an entry pointer points to a specific node in the list, then assuming pp is a pointer of pointer, we can remove the entry without using any conditionals when traversing the list by just doing thing like the following: *pp = entry->next.

    Here are my codes:

    struct ListNode* removeElements(struct ListNode* head, int val) {
        for (struct ListNode **curr = &head; *curr; ) {
            struct ListNode *entry = *curr;
            if (entry->val == val) *curr = entry->next;
            else curr = &entry->next;
        }
        return head;
    }

Log in to reply
 

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