这里使用了额外的存储空间,可以使用双指针来实现,不需额外的存储空间.
/** * 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 head; ListNode pre = head; ListNode runner = head.next; while(runner != null){ if(pre.val == runner.val){ pre.next = runner.next; runner =runner.next; continue; } pre = pre.next; runner = runner.next; } return head; } }