输入:head = [1,2,6,3,4,5,6], val = 6
输出:[1,2,3,4,5]
解题关键:若使用 cur 表示当前节点,则删除下一个节点方法:cur.next = cur.next.next
解题思路:
class Solution
{
public:
ListNode *removeElements(ListNode *head, int val)
{
ListNode* dumpyNode = new ListNode(0, head);
ListNode* cur = dumpyNode;
while(cur->next != nullptr) {
if (cur->next->val == val) {
cur->next = cur->next->next;
}else {
cur = cur->next;
}
}
return dumpyNode->next;
}
};