很简单的一题,需要注意的是如果某结点重复了记得将其删除。
ListNode *deleteDuplicates(ListNode *head) { if (head == nullptr) return nullptr; ListNode *prev = head; for (ListNode *cur = head->next; cur != nullptr; cur = cur->next) { if (cur->val == prev->val) { prev->next = cur->next; delete cur; } else prev->next = cur; } }
这题采用递归来做,当两结点不等时,注意递归调用的形式。
ListNode *deleteDuplicates2(ListNode *head) { if (!head || !head->next)return head; ListNode *p = head->next; if (p == head) { while (p&&p==head) { ListNode *temp = p; p = p->next; delete temp; } delete head; return deleteDuplicates2(p); } else { head->next=deleteDuplicates2(head->next); return head; } }