Given a sorted linked list, delete all duplicates such this each element appear only once.
For example,
Given 1->1->2 , return 1->2 .
Given 1->1->2->3->3 , return 1->2->3 .
The idea is very simple, because the good sort, is to judge the next is not bigger than it is good, if large, then skip the next direct link to the next next. But notice at this point, consider if this is the case of 1->1->1, when you delete the second 1, the pointer must be kept in the first position, so as to determine whether the 1 and then the next 1 is not equal (that is, the first 1 and the 3rd 1). The only thing that needs special attention is the last two, because you want to p.next=p.next.next to delete, so for the last two does not exist next next, so directly equal to null just fine
Package Testandfun;public class Deleteduplicates {public static void main (String args[]) {deleteduplicates DP = new DeleteD Uplicates (); ListNode head = new ListNode (3); ListNode p1 = new ListNode (3); head.next=p1; ListNode P2 = new ListNode (3);p 1.next = p2; ListNode p3 = new ListNode (3);p 2.next = p3; ListNode P4 = new ListNode;p 3.next = P4;prinf (head);p Rinf (Dp.deletedup (Head));} private static void Prinf (ListNode input) {while (input!=null) {System.out.print (input.val+ "); input = Input.next;} System.out.println ();} Public ListNode Deletedup (ListNode head) {if (head==null| | Head.next==null) return head;//if No head, what is should I do? ListNode p=head;int i=0;//system.out.println (p.val+ "and" +p.next.val); while (p.next! = null) {if (p.val==p.next.val &&p.next.next!=null) {//system.out.println ("go First" +p.val);//"^^" +p.next.val+ "percent" +p.next.next.val); P.next=p.next.next;continue;//if this and next equal, we should stay in the case Next.next is equal this}else if (p.val ==p.next.val&&P.next.next==null) {//system.out.println ("go Second" +p.val);p. next=null;continue;} System.out.println (p.val+ "Round" +i++);p =p.next;if (p==null) break;} System.out.print (Head.val); return head;}}
"Leetcode" Remove duplicates from Sorted List in JAVA