class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *pseudo_head = new ListNode(0);
pseudo_head>next = head;
ListNode *cur = pseudo_head;
while(cur){
if(cur>next && cur>next>val == val) cur>next = cur>next>next;
else cur = cur>next;
}
return pseudo_head>next;
}
};
Concise C++ solution with pseudo ListHead


It appears that we had the same idea.
public ListNode removeElements(ListNode head, int val) { ListNode pseudoHead = new ListNode(0); pseudoHead.next = head; ListNode iter = pseudoHead; while(iter.next != null) { // The next node match the value. if (iter.next.val == val) { // remove the next node. iter.next = iter.next.next; } else { iter = iter.next; } } return pseudoHead.next; }

Cool solution!
But I am wondering when you do this assignment "ListNode* cur = pseudo_head;", in while loop when the pointer cur changes to point to other address, would pseudo_head change accordingly? If not, what would happen to "head" pointer if you only doing something with "cur" pointer?
Ex:ListNode *pseudo_head = new ListNode(0); pseudo_head>next = head; ListNode *cur = pseudo_head; cur = cur>next;
where would "peudo_head" point to after running the code above?

My solution is similar with yours, except that I delete the memory of the delete node.
/** * Definition for singlylinked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* dummy_head = new ListNode(INT_MAX); dummy_head>next = head; ListNode* reserve_head = dummy_head; while(dummy_head != nullptr && dummy_head>next != nullptr) { if(dummy_head>next>val == val) { ListNode* tmp = dummy_head>next; dummy_head>next = dummy_head>next>next; delete tmp; } else { dummy_head = dummy_head>next; } } return reserve_head>next; } };