难度

  • 简单
  • 中等
  • [ ] 困难

    标签

    链表

    题目描述

    编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

    示例1:

    1. 输入:[1, 2, 3, 3, 2, 1]
    2. 输出:[1, 2, 3]

    实例2:

    1. 输入:[1, 1, 1, 1, 2]
    2. 输出:[1, 2]

    题解

    1. 哈希表

    1. /**
    2. * Definition for singly-linked list.
    3. * public class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) { val = x; }
    7. * }
    8. */
    9. import java.util.HashSet;
    10. class Solution {
    11. public ListNode removeDuplicateNodes(ListNode head) {
    12. if(head == null) {
    13. return null;
    14. }
    15. ListNode cur = head;
    16. HashSet<Integer> set = new HashSet();
    17. while(cur != null && cur.next != null) {
    18. set.add(cur.val);
    19. if(set.contains(cur.next.val)) {
    20. cur.next = cur.next.next;
    21. } else {
    22. cur = cur.next;
    23. }
    24. }
    25. return head;
    26. }
    27. }