203. Remove Linked List Elements
程序员文章站
2024-02-19 08:36:18
...
203. Remove Linked List Elements
方法1: iterative
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (!head) return head;
ListNode * prev = new ListNode(-1);
ListNode * newHead = prev;
prev -> next = head;
while (head){
if (head -> val == val) {
prev -> next = head -> next;
head = head -> next;
}
else {
prev = prev -> next;
head = head -> next;
}
}
return newHead->next;
}
};
方法2: recursion
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
if (!head) return head;
head -> next = removeElements(head -> next, val);
if (head -> val == val){
return head -> next;
}
return head;
}
};
推荐阅读
-
203. Remove Linked List Elements
-
leetcode 203. Remove Linked List Elements
-
LeetCode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
Leetcode 203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
203. Remove Linked List Elements
-
【leetcode】203. Remove Linked List Elements
-
LeetCode(52)-Remove Linked List Elements