My C++ Solution


  • 0
    class Solution {
    public:
        ListNode* removeElements(ListNode* head, int val) {
            if (!head) return head;
    		ListNode* front = new ListNode(0);
    		front->next = head;
    		head = front;                                      // insert head node
    		ListNode* prev = head->next, *post = head;
    		while (prev){
    			if (prev->val == val){
    				post->next = prev->next;
    				ListNode* temp = prev;
    				prev = prev->next;
    				delete temp;
    			}
    			else{
    				post = post->next;
    				prev = prev->next;
    			}
    		}
    		return front->next;
        }
    };

Log in to reply
 

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