-
Notifications
You must be signed in to change notification settings - Fork 0
203_RemoveLinkedListElements
a920604a edited this page Apr 14, 2023
·
1 revision
title: 203. Remove Linked List Elements
tags:
- Linked List
- Two Pointers
categories: leetcode
comments: false
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *slow = new ListNode(-1), *fast=head, *ret = slow;
slow->next = head;
while(fast){
if(fast->val!=val) {
slow->next = fast;
slow=slow->next;
}
fast=fast->next;
}
slow->next = nullptr;
return ret->next;
}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *cur = new ListNode(-1), *ret = cur;
cur->next = head;
while(cur){
if(cur->next && cur->next->val == val) cur->next = cur->next->next;
else cur = cur->next;
}
return ret->next;
}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode *cur = new ListNode(-1), *ret = cur;
cur->next = head;
while(cur){
while(cur->next && cur->next->val ==val) cur->next=cur->next->next;
cur = cur->next;
}
return ret->next;
}
};
- time complexity
O(n)
- space complexity
O(1)
footer