Skip to content

Instantly share code, notes, and snippets.

@icameling
Last active July 18, 2022 08:04
Show Gist options
  • Save icameling/9688ed2bd6367de96f844f8b834bd2d1 to your computer and use it in GitHub Desktop.
Save icameling/9688ed2bd6367de96f844f8b834bd2d1 to your computer and use it in GitHub Desktop.
#链表 #移除链表元素 #leetcode
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
// delete head node
while (head != nullptr && head->val == val) {
ListNode* tmp = head;
head = head->next;
delete tmp;
}
// delete non head node
ListNode* cur = head;
while (cur != nullptr && cur->next != nullptr) {
if (cur->next->val == val) {
ListNode* tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
} else {
cur = cur->next;
}
}
return head;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment