【刷题日记】链表-移除链表元素-L203-Easy
给你一个链表的头节点 head 和一个整数 val ,请你删除链表中所有满足 Node.val == val 的节点,并返回 新的头节点 。
思路
学习点
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
class Solution { public: ListNode* removeElements(ListNode* head, int val) { while (head != nullptr && head->val == val) { head = head->next; } if (head == nullptr) { return head; }
ListNode* p = head; while (p->next != nullptr) { if (p->next->val == val) { auto temp = p->next; p->next = p->next->next; delete temp; } else { p = p->next; } } return head; } };
|