My simple C++ solution


  • -1
    M
    /**
    
    • Definition for singly-linked list.

    • struct ListNode {

    • int val;
      
    • ListNode *next;
      
    • ListNode(int x) : val(x), next(NULL) {}
      
    • };
      /
      class Solution {
      public:
      ListNode
      removeElements(ListNode* head, int val) {
      ListNode *pNode = head;
      ListNode *pPrev = NULL;

       while (pNode != NULL) {
           if (pNode->val == val) {
               if (pPrev == NULL) {
                   ListNode *pDel = pNode;
                   pNode = pNode->next;
                   head = pNode;
                   delete pDel;
                   continue;
               } else {
                   pPrev->next = pNode->next;
                   ListNode *pDel = pNode;
                   pNode = pNode->next;
                   delete pDel;
                   continue;
               }
           }
           pPrev = pNode;
           pNode = pNode->next;
       }
       
       return head;
      

      }
      };


Log in to reply
 

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