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