题目:image.png


个人解答:

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode() : val(0), next(nullptr) {}
  7. * ListNode(int x) : val(x), next(nullptr) {}
  8. * ListNode(int x, ListNode *next) : val(x), next(next) {}
  9. * };
  10. */
  11. class Solution {
  12. public:
  13. ListNode* deleteDuplicates(ListNode* head) {
  14. ListNode* result = new ListNode();
  15. ListNode* result_head = result;
  16. ListNode* node_symbol = new ListNode(9999);
  17. int count = 0;
  18. if(head==nullptr||head->next==nullptr)
  19. return head;
  20. while(head->next!=nullptr)
  21. {
  22. if(head->val != head->next->val)
  23. {
  24. if(head->val!=node_symbol->val)
  25. {
  26. result->next = new ListNode(head->val);
  27. result=result->next;
  28. }
  29. }
  30. node_symbol = head;
  31. head = head->next;
  32. }
  33. if(head->val!=node_symbol->val)
  34. {
  35. result->next = new ListNode(head->val);
  36. result=result->next;
  37. }
  38. return result_head->next;
  39. }
  40. };

官方解答:

细节

需要注意 \textit{cur.next}cur.next 以及 \textit{cur.next.next}cur.next.next 可能为空节点,如果不加以判断,可能会产生运行错误。

代码

注意下面 \texttt{C++}C++ 代码中并没有释放被删除的链表节点以及哑节点的空间。如果在面试中遇到本题,读者需要针对这一细节与面试官进行沟通。

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head) {
        if (!head) {
            return head;
        }

        ListNode* dummy = new ListNode(0, head);

        ListNode* cur = dummy;
        while (cur->next && cur->next->next) {
            if (cur->next->val == cur->next->next->val) {
                int x = cur->next->val;
                while (cur->next && cur->next->val == x) {
                    cur->next = cur->next->next;
                }
            }
            else {
                cur = cur->next;
            }
        }

        return dummy->next;
    }
};