题目

给定一个排序链表,删除所有重复的元素,使得每个元素只出现一次。

示例 1:

输入: 1->1->2
输出: 1->2
示例 2:

输入: 1->1->2->3->3
输出: 1->2->3

解析

由于已经是排序链表,直接判断next的值是不是等于当前节点的值

代码

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. ListNode* deleteDuplicates(ListNode* head) {
  12. ListNode* cur = head;
  13. while (cur && cur->next) {
  14. if (cur->val == cur->next->val) cur->next = cur->next->next;
  15. else cur = cur->next;
  16. }
  17. return head;
  18. }
  19. };

如果链表是无序的,用unordered_set记录即可

  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. // private:
  11. // unordered_set<int> record;
  12. public:
  13. ListNode* deleteDuplicates(ListNode* head) {
  14. // ListNode* h = head;
  15. ListNode* dummy = new ListNode(-1);
  16. dummy->next = head;
  17. ListNode* pre = dummy;
  18. ListNode* cur = dummy->next;
  19. while (cur) {
  20. if (record.find(cur->val) == record.end()) {
  21. record.insert(cur->val);
  22. pre = pre->next;
  23. cur = cur->next;
  24. }
  25. else {
  26. pre->next = cur->next;
  27. cur = cur->next;
  28. }
  29. }
  30. return dummy->next;
  31. }
  32. };