Two points of experience: 1. Using the virtual header flexibly in the connected Title will reduce a lot of work; 2. the linked list is often judged at the end of the question to prevent the corner case
Package Level3; import Utility. listNode;/*** Remove Duplicates from Sorted List II *** 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. **/public class S82 {public static void main (String [] args) {ListNode head = new ListNode (1); ListNode n1 = new ListNode (2); ListNode n2 = new ListNode (2); ListNode n3 = new ListNode (3); ListNode n4 = new ListNode (3 ); listNode n5 = new ListNode (4); ListNode n6 = new ListNode (5); head. next = n1; n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; head. print (); ListNode h = deleteDuplicates (head); h. print ();} public static ListNode deleteDuplicates (ListNode head) {if (Head = null) {return null;} // using dummyHead to add a virtual header effectively reduces the workload !! ListNode dummyHead = new ListNode (Integer. MIN_VALUE); dummyHead. next = head; ListNode pre = dummyHead; ListNode cur = pre. next; ListNode next = cur. next; boolean dup = false; // judge whether there are repeated while (true) {if (next = null) {break;} if (cur. val! = Next. val) {if (dup) {// if there are duplicates, skip the pre. next = next; dup = false; // restore dup} else {// otherwise pre = cur;} cur = next; next = next. next;} else if (cur. val = next. val) {dup = true; next = next. next;} // scan the tail, for example, {1, 1}, and finally judge if (dup) {pre. next = next;} return dummyHead. next ;}}