My solution and explaination.


  • 0
    L

    class Solution {
    public:
    ListNode* removeElements(ListNode* head, int val) {
    if(head == NULL) return NULL;
    ListNode *h;
    h->next = head;
    ListNode *p = h; //point p and h point to head;

        while(head != NULL){
            if(head && head->val == val){                  //if nodes value equal val;
                while(head && head->val == val){
                    head = head->next;                        //find until the node not equal val
                }
                if(head == NULL){                               //if head == NULL, it means that all nodes after last step equal val.
                    h->next = NULL;                            //then h next point to the tail(i.e. NULL)
                    break;
                }
                else{                                                  //if head not NULL, means find one node which not equal val and there is still nodes`s value not equal val.
                    h->next = head;                           //h next point to the nodes which not equal val
                    h = h->next;                                 //move h to the node which not equal val. it will point to next step result.
                    head = head->next;                    //head point to next value.
                }
            }
            else{                                                    //if nodes value not equal val, head and h should point to next node;
                head = head->next;
                h = h->next;
            }
        }
        return p->next;
    }
    

    };


  • 0
    S

    My answer is similar to yours.

        ListNode curr = head;
        ListNode last = null;
        while(curr!=null){
            if(curr.val==val){
                if(curr==head){
                    head = curr.next;
                }else{
                    last.next = curr.next;
                }
            }else{
                last = curr;
            }
            curr = curr.next;
        }
        return head;

Log in to reply
 

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