c++ solution, use dummy head.


  • 0
    class Solution {
    public:
      ListNode* removeElements(ListNode* head, int val) {
        if (head == NULL)
        {
          return head;
        }
    
        ListNode *dummy = new ListNode(-1);
        dummy -> next = head;
    
        ListNode *pre;
        pre = dummy;
    
        while (head != NULL)
        {
          ListNode *pnext = head -> next;
          if (head -> val == val)
          {
    	pre -> next = pnext;
          }
          else
          {
    	pre = head;
          }
          head = head -> next;
        }
        
        return dummy -> next;
      }
    };
    

Log in to reply
 

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