[Leetcode-java] Remove duplicates from Sorted List II optimized version

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.