AC, simple c++ code, easy to understand


  • 0
    L
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            
            while (NULL != head && head->val == val) head = head->next;
            if(NULL == head || (NULL == head->next && head->val == val)) return NULL;
            
            ListNode* node = head->next;
            ListNode* pren = head;
            while(NULL != node) {
                if(node->val == val) {
                    pren->next = node->next;
                    node = node->next;
                } else {
                    pren = node;
                    node = node->next;
                }
            }
            
            return head;
        }
    };

  • -1
    G

    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
    while (head!=NULL && head->val == val) head = head->next;
    if(head == NULL){
    return NULL;
    }

        ListNode *node = head->next;
        ListNode * preNode = head;
        while (node != NULL){
            if(node->val == val){
                preNode->next = node->next;
                node = node->next;
            }else{
                preNode = node;
                node = node->next;
            }
        }
        return head;
    }
    

    };


Log in to reply
 

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