Problem: 203. 移除链表元素
思路
基本的链表删除
脑瘫的错误
遍历链表是while(current->next != nullptr)
一开始记不得了
复杂度
$O(n)$
$O(1)$
Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* dummy = new ListNode(0);dummy->next = head; ListNode *pre = dummy,*cur = head; while (cur != nullptr) { if (cur->val == val) { pre->next = cur->next; delete cur; cur = pre->next; } else { pre = cur; cur = cur->next; } } return dummy->next; } };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public: ListNode* removeElements(ListNode* head, int val) { ListNode* dummyHead = new ListNode(0); dummyHead->next = head; ListNode* current = dummyHead;
while(current->next != nullptr) { if(current->next->val == val) { ListNode* p = current->next; current->next = current->next->next; delete p; }else{ current = current->next; } }
head = dummyHead->next; delete dummyHead; return head; } };
|