ListNode* removeElements(ListNode* head, int val){ ListNode* preHead = new ListNode(-1); ListNode* cur = preHead; while (head) { if (head->val != val) { auto item = new ListNode(head->val); cur->next = item; cur = item; } head = head->next; } return preHead->next; }
它山之石
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
ListNode* removeElements(ListNode* head, int val){ if (!head) return head; ListNode* h = head; while (h && h->next) { if (h->next->val == val) { ListNode* temp = h->next; h->next = h->next->next; delete temp; } else h = h->next; }
if (head->val == val) head = head->next; return head; }