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