还不快抢沙发

添加新评论

删除链表中等于给定值 val 的所有元素。 示例 给定: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6 返回: 1 --> 2 --> 3 --> 4 --> 5 解答: ``` 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; } ``` 它山之石 ``` 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; } ```