Remove Duplicates from Sorted List II @ LeetCode

Source: Internet
Author: User

Two points of experience: 1. Using the virtual header flexibly in the connected Title will reduce a lot of work; 2. the linked list is often judged at the end of the question to prevent the corner case

Package Level3; import Utility. listNode;/*** Remove Duplicates from Sorted List II *** Given a sorted linked list, delete all nodes that have 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. **/public class S82 {public static void main (String [] args) {ListNode head = new ListNode (1); ListNode n1 = new ListNode (2); ListNode n2 = new ListNode (2); ListNode n3 = new ListNode (3); ListNode n4 = new ListNode (3 ); listNode n5 = new ListNode (4); ListNode n6 = new ListNode (5); head. next = n1; n1.next = n2; n2.next = n3; n3.next = n4; n4.next = n5; n5.next = n6; head. print (); ListNode h = deleteDuplicates (head); h. print ();} public static ListNode deleteDuplicates (ListNode head) {if (Head = null) {return null;} // using dummyHead to add a virtual header effectively reduces the workload !! ListNode dummyHead = new ListNode (Integer. MIN_VALUE); dummyHead. next = head; ListNode pre = dummyHead; ListNode cur = pre. next; ListNode next = cur. next; boolean dup = false; // judge whether there are repeated while (true) {if (next = null) {break;} if (cur. val! = Next. val) {if (dup) {// if there are duplicates, skip the pre. next = next; dup = false; // restore dup} else {// otherwise pre = cur;} cur = next; next = next. next;} else if (cur. val = next. val) {dup = true; next = next. next;} // scan the tail, for example, {1, 1}, and finally judge if (dup) {pre. next = next;} return dummyHead. next ;}}

 

 

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.