Leetcode "Remove duplicates from Sorted List II" Python implementation

Source: Internet
Author: User

title :

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 .

code : OJ online test via 288 ms

1 #Definition for singly-linked list.2 #class ListNode:3 #def __init__ (self, x):4 #self.val = x5 #Self.next = None6 7 classSolution:8     #@param head, a listnode9     #@return a ListNodeTen     defdeleteduplicates (Self, head): One         ifHead isNoneorHead.next isNone: A             returnHead -          -Dummyhead =listnode (0) theDummyhead.next =Head -          -p =Dummyhead -          whileP.next is  notNone andP.next.next is  notNone: +TMP =P -              whileTmp.next.val = =Tmp.next.next.val: +TMP =Tmp.next A                 ifTmp.next.next isNone: at                      Break -             ifTMP = =P: -p =P.next -             Else: -                 ifTmp.next.next is  notNone: -P.next =Tmp.next.next in                 Else: -P.next =Tmp.next.next to                      Break +         returnDummyhead.next

Ideas :

Set up the virtual table header Hummyhead to handle the linked list in a convenient way

P.next always points to the element to compare

A while loop is then nested in a while loop, skipping over the repeating elements.

If a repeating element is encountered: P does not move, p.next changes; If duplicate elements are not encountered, P=p.next

Tips: It is best to add a logical judgment pointer before using the pointer is not empty

Leetcode "Remove duplicates from Sorted List II" Python implementation

Related Article

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.