Simple C Time O(n)


  • 0
    F
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     struct ListNode *next;
     * };
     */
    struct ListNode* removeElements(struct ListNode* head, int val) {
        struct ListNode* cur = head;
        struct ListNode* pre = NULL;
        
        while(cur){
            if(cur->val == val){
                if (!pre){
                    pre = cur;
                    cur = cur->next;
                    free(pre);
                    pre = NULL;
                    head = cur;
                }
                else{
                    pre->next = cur->next;
                    free(cur);
                    cur = pre->next;
                }
            }
            else{
                pre = cur;
                cur = cur->next;
            }            
        }
        return head;
    }
    

Log in to reply
 

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