题解 | 删除有序链表中重复的元素-I (四种方法)
删除有序链表中重复的元素-I
https://www.nowcoder.com/practice/c087914fae584da886a0091e877f2c79
/** * 递归法 */ ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) { return head; } head->next = deleteDuplicates(head->next); return head->val == head->next->val ? head->next : head; } /** * 迭代法 单指针 */ ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) { return head; } ListNode* cur = head; while (cur->next) { if (cur->val == cur->next->val) { cur->next = cur->next->next; } else { cur = cur->next; } } return head; } /*迭代法 双指针*/ ListNode* deleteDuplicates(ListNode* head) { if (!head || !head->next) { return head; } ListNode* pre = head; ListNode* cur = head->next; while (cur) { if (pre->val == cur->val) { pre->next = cur->next; } else { pre = pre->next; } cur = cur->next; } return head; } /* 增加虚拟头结点 */ ListNode* deleteDuplicates(ListNode* head) { ListNode* dummyHead = new ListNode(1000); dummyHead->next = head; ListNode* cur = dummyHead; while (cur->next) { if (cur->val == cur->next->val) { cur->next = cur->next->next; } else { cur = cur->next; } } ListNode* retNode = dummyHead->next; delete dummyHead; return retNode; }