Remove all elements from a linked list of integers that have value val.
Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5
删除链表中指定值,找到其前一个节点即可,将 next 指向下一个节点即可。
设置一个哑节点来防止头节点被删除造成无法返回新链表。
/** * 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) { if (head == nullptr) return 0; ListNode* dummy = new ListNode(0); dummy->next = head; ListNode* cur = dummy; while (cur->next) { if (cur->next->val == val) { cur->next = cur->next->next; } else { cur = cur->next; } } return dummy->next; } }; // 26 ms