LC.82. Remove Duplicates from Sorted List II
https://leetcode.com/problems/remove-duplicates-from-sorted-list-ii/description/
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
time: o(n) complexity: o(1)
1 public ListNode deleteDuplicates(ListNode head) { 2 if (head == null || head.next != null ) return head ; 3 ListNode dummy = new ListNode(0) ; 4 //注意,如果 CURR = HEAD 的话, 那第一个节点是没有办法删除掉的! 所以要灵活的运用CURR 5 ListNode curr = dummy; 6 dummy.next = head ; 7 /* 8 * 1->2->3->3->4->4->5, return 1->2->5. 9 * c c c-----c 10 * */ 11 while (curr.next != null && curr.next.next != null){ 12 if (curr.next.val == curr.next.next.val ){ 13 int val= curr.next.val; 14 //凡事循环了,就要CHECK NPE 15 while(curr.next != null && curr.next.val == val){ 16 curr.next = curr.next.next ; 17 } 18 } else{ 19 curr = curr.next ; 20 } 21 } 22 return dummy.next ; 23 }