[Leetcode] [Java] Remove duplicates from Sorted List II

Source: Internet
Author: User

Test Instructions:

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 .

Title:

Given an ordered list, all duplicate nodes are deleted, and the remainder are the different node elements in the original linked list.

Like what

Given 1->2->3->3->4->4->5, returns 1->2->5 .

Given 1->1->1->2->3, returns 2->3 .

Algorithm Analysis:

Sets the double pointer before and after the pointer encounters a repeating element and iterates until the end of the repetition, before the pointer points to the back pointer, which skips over all repeating elements.

AC Code:

<span style= "Font-family:microsoft yahei;font-size:12px;" >public class Solution {    public  ListNode deleteduplicates (listnode head)     {        ListNode pre;        ListNode cur;        ListNode newhead = new ListNode (0);        Newhead.next=head;        if (head==null| | Head.next==null)        return head;        Pre=newhead;        Cur=head;        while (Cur.next!=null)        {        if (cur.next.val==cur.val)//processing the first few elements of the same example, such as 1 1 1 2 3 4         {while        ( Cur.next.val==cur.val)        {        cur=cur.next;        if (cur.next==null)//processing at the end several elements of the same example 1 2 3 4 5 5 5 break        ;        Pre.next=cur.next;        Pre=pre.next;        Cur=cur.next;        if (cur==null) break        ;        }        else//processing the first few elements of a different example 1 2 3 4 5        {        pre=pre.next;        Cur=cur.next;        }        }    return newhead.next;}    } </span>


Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source

[Leetcode] [Java] Remove duplicates from Sorted List II

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.