https://leetcode.com/problems/remove-linked-list-elements/description/
Solution 0. Iteration 1. use pointer to a pointer.
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
ListNode** pn = &head;
while(*pn) {
if((*pn)->val == val) {
*pn = (*pn)->next;
}
else {
pn = &(*pn)->next;
}
}
return head;
}
Solution 1. Recursion 0
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
head->next = removeElements(head->next, val);
ListNode* node = head;
if(head->val == val) {
head = head->next;
}
return head;
}
Solution 1.1 Recursion 1
void remove(ListNode*& node, int val) {
if(!node) return;
if(node->val == val) {
node = node->next;
remove(node, val);
}
else remove(node->next, val);
}
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
remove(head, val);
return head;
}
Solution 2. Iteration 2
ListNode* removeElements(ListNode* head, int val) {
if(!head) return head;
ListNode* node = head, *pre = head;
while(node) {
if(node->val == val) {
if(node == head) {
head = head->next;
node = head;
pre = head;
}
else {
pre->next = node->next;
node = pre->next;
}
}
else {
pre = node;
node = node->next;
}
}
return head;
}
No comments:
Post a Comment