class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if(!head) return NULL;
ListNode* newHead = new ListNode(INT_MIN);
newHead>next = head;
ListNode* cur = head;
ListNode* prev = newHead;
while(cur)
{
if(cur>val == val)
{
ListNode* t = cur;
prev>next = cur>next;
cur = cur>next;
delete t;
continue;
}
prev = cur;
cur = cur>next;
}
ListNode* t = newHead>next;
delete newHead;
return t;
}
};
Simple C++ Solution


class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode *p = (ListNode *)malloc(sizeof(struct ListNode));// p's next is head (p is just a pointer) p>next = head; head = p; while(head){ ListNode *np = head>next;// np try to point to the next proper ListNode (np is another pointer) while(np && np>val == val) np = np>next; head>next = np; head = np; } return p>next; } };
Note: I am lazy, so I skipped the process to return the free space. It is a bad habit...