Leetcode "Merge Sorted Lists" Python implementation

Source: Internet
Author: User

title :

Merge sorted linked lists and return it as a new list. The new list should is made by splicing together the nodes of the first of the lists.

code : OJ online test via runtime:208 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 listnodes9     #@return a ListNodeTen     defmergetwolists (self, L1, L2): One         ifL1 isNone: A             returnL2 -         ifL2 isNone: -             returnL1 the          -Dummyhead =listnode (0) -Dummyhead.next =None -p =Dummyhead +          whileL1 is  notNone andL2 is  notNone: -             ifL1.val >L2.val: +P.next =L2 AL2 =L2.next at             Else: -P.next =L1 -L1 =L1.next -p =P.next -         ifL1 is  notNone: -P.next =L1 in         Else: -P.next =L2 to         returnDummyhead.next

Ideas :

Virtual table Head Dummyhead set up do not move, set a P=hummyhead, and then start from the processing P.next, and finally return to Hummyhead to get the correct results

The two-table pointer moves one step at a pace and determines which insert p.next by comparing the size of the Val

Notice that each time you execute the judgment, move the pointer p=p.next

Leetcode "Merge Sorted Lists" 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.