题目:


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(0,head);
  15. ListNode* cur = result;
  16. if(!head)
  17. return head;
  18. while(cur->next&&cur->next->next)
  19. {
  20. if(cur->next->val==cur->next->next->val)
  21. {
  22. cur->next = cur->next->next;
  23. }
  24. else
  25. {
  26. cur=cur->next;
  27. }
  28. }
  29. if(cur->next&&cur->val!=cur->next->val)
  30. cur = cur->next;
  31. return result->next;
  32. }
  33. };

官方解答:

细节

当我们遍历到链表的最后一个节点时,(简单)83.删除排序链表中的重复元素 - 图2 为空节点,如果不加以判断,访问 (简单)83.删除排序链表中的重复元素 - 图3对应的元素会产生运行错误。因此我们只需要遍历到链表的最后一个节点,而不需要遍历完整个链表。

代码

注意下面(简单)83.删除排序链表中的重复元素 - 图4代码中并没有释放被删除的链表节点的空间。如果在面试中遇到本题,读者需要针对这一细节与面试官进行沟通。

  1. class Solution {
  2. public:
  3. ListNode* deleteDuplicates(ListNode* head) {
  4. if (!head) {
  5. return head;
  6. }
  7. ListNode* cur = head;
  8. while (cur->next) {
  9. if (cur->val == cur->next->val) {
  10. cur->next = cur->next->next;
  11. }
  12. else {
  13. cur = cur->next;
  14. }
  15. }
  16. return head;
  17. }
  18. };

image.png