Last active
July 18, 2022 08:04
-
-
Save icameling/9688ed2bd6367de96f844f8b834bd2d1 to your computer and use it in GitHub Desktop.
#链表 #移除链表元素 #leetcode
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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