Topic:
Given a sorted linked list, delete all nodes that has 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 .
Original idea: Save the previous pointer, so that in the repetition, you can directly point to the new position, it should be noted that the beginning, the need to make additional judgment whether there is repetition, in order to form a misplaced pointer.
Original code:
Public classSolution { PublicListNode deleteduplicates (ListNode head) {ListNode req=Head; ListNode Pre=Head; //determine if there is a repetition of the initial while(Head! =NULL) {Head= Head.next;//until there is no repetition, the head is next to the pre if(Head! =NULL&& Pre.val = =head.val) { Do{Head=Head.next; } while(head!=NULL&& Head.val = =pre.val); Pre=Head; Req=Head; }Else Break; } //process, the pre is always in front of the head while(Head! =NULL) {Head=Head.next; if(head!=NULL&& Pre.next.val = =head.val) { Do{Head=Head.next; } while(head!=NULL&& Head.val = =pre.next.val); Pre.next=Head; } ElsePre =Pre.next; } returnreq; }}
Modify the idea: You can create a virtual table header, next point to head, so that the original code in the initial part of the extra judgment to optimize the code is very concise.
Modified code:
Public classSolution { PublicListNode deleteduplicates (ListNode head) {ListNode dunmy=NewListNode (Integer.min_value); Dunmy.next=Head; ListNode Pre=dunmy; while(Head! =NULL) {Head=Head.next; if(head!=NULL&& Pre.next.val = =head.val) { Do{Head=Head.next; } while(head!=NULL&& Head.val = =pre.next.val); Pre.next=Head; } ElsePre =Pre.next; } returnDunmy.next; }}
[Leetcode-java] Remove duplicates from Sorted List II optimized version