[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, delete all the repeated nodes. The remainder is not the same node element in the original list.

Example.

Given 1->2->3->3->4->4->5. Return 1->2->5 .

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

Algorithm Analysis:

Sets the front and rear double pointers. After the pointer encounters a repeating element, it traverses until the end of the iteration, and then the front pointer points to the back pointer, which skips over all the repeated 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 sample Example 1 1 1 2 3 4         {while        ( Cur.next.val==cur.val)        {        cur=cur.next;        if (cur.next==null)//Process The end of several elements 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 are not the same example 1 2 3 4 5        {        pre=pre.next;        Cur=cur.next;        }        }    return newhead.next;}    } </span>


[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.