这里使用了额外的存储空间,可以使用双指针来实现,不需额外的存储空间.
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) { return null; } HashSet<Integer> s = new HashSet<Integer>(); ListNode pre = null; ListNode cur = head; while(cur != null){ if(s.contains(cur.val)){ /*if there‘s a duplicate element, skip the current element*/ pre.next = cur.next; cur = cur.next; }else{ s.add(cur.val); pre = cur; cur = cur.next; } } return head; } }
双指针,不使用额外存储空间
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode deleteDuplicates(ListNode head) { if(head == null) return null; ListNode pre = head; ListNode p = head.next; while(p != null){ if(pre.val == p.val){ pre.next = p.next; p = p.next; continue; } p = p.next; pre = pre.next; } return head; } }