Remove Linked List Elements
Description
Remove all elements from a linked list of integers that have value val.
Example Given 1->2->3->3->4->5->3, val = 3, you should return the list as 1->2->4->5
Link
Method
- x
- x
Example
- 1
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: /** * @param head a ListNode * @param val an integer * @return a ListNode */ ListNode *removeElements(ListNode *head, int val) { // Write your code here if (!head) { return nullptr; } ListNode dummy(0); dummy.next = head; ListNode* prev = &dummy; while (prev->next) { if (prev->next->val != val) { prev = prev->next; continue; } ListNode* tmp = prev->next; prev->next = prev->next->next; delete tmp; } return dummy.next; } };
Similar problems
x
Tags
x