Remove duplicates from Sorted List II

Source: Internet
Author: User

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 .

Delete the duplicate numbers in the list, and note that this is the number that will be removed once the numbers have been duplicated. So how to completely remove is a technical live. Of course, in order to deal with the deletion of the head node, dummy node will also be re-emerged.

In Python, note that deleting a node in LinkedList does not need to be deleted, but instead allows the preamble to point to its post-order, skipping the node. In order to be easy to delete, we still know the pre-order node, we need a pre to save the pre-order, to establish the connection (especially to skip the element's connection). Each node is judged to be equal to the post-order node value, and if equal, all nodes equal to this value are found and deleted. The code is as follows:

classsolution (object):defdeleteduplicates (Self, head):""": Type Head:ListNode:rtype:ListNode"""        if  notHead:returnNone Dummy= ListNode (-1) Dummy.next=Head prev=Dummy whileHead andHead.next:ifHead.val = =Head.next.val: whileHead andHead.next andHead.val = =Head.next.val:head=Head.next Head=Head.next # handles the last node with an equal value Prev.next=HeadElse: Prev=Prev.next Head=Head.nextreturnDummy.next

Time complexity O (n), Spatial complexity O (1).

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.