. Merge Sorted Lists--python

Source: Internet
Author: User

Topic:

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.

Nothing to do the problem, the title is said two sorted list of linked lists together, is still sorted well, that is, the value of the list from small to large.

Code:

Thus, create a new linked list, next with two linked list of the current position to compare, who the small put who. When a linked list is finished, it means that the remaining elements of the other list are relatively large and then put in.

The topic is simple because it is already a list of two sorted lists.

Here's the Python code, and there's the test process.

#Coding:utf-8#Definition for singly-linked list.classListNode (object):def __init__(self, x): Self.val=x Self.next=Noneclasssolution (object):defmergetwolists (self, L1, L2):""": Type L1:ListNode:type l2:ListNode:rtype:ListNode"""        if  notL1 and  notL2:returnresult=ListNode (0) L=result whileL1 andL2:ifL1.val <L2.val:l.next=L1 L1=L1.nextElse: L.next=L2 L2=L2.next#after merging the next bit of the list, the current position has just been assigned a valueL =L.next#put the rest of the list in the back.L.next = L1orL2#returns the merged list starts with the second object, the first object is created by itself ListNode (0)        returnResult.nextif __name__=='__main__':    #create L1 and L2 two linked lists, note that sorting good requires arr1 and arr2 numbers from small to largeARR1 = [A] ARR2= [5,6,7] L1=ListNode (arr1[0]) P1=L1 L2=ListNode (arr2[0]) P2=L2 forIinchArr1[1:]: P1.next=ListNode (i) P1=P1.next forIinchArr2[1:]: P2.next=ListNode (i) P2=P2.next S=solution ()#fusion of two linked listsQ=s.mergetwolists (L1,L2)

. Merge Sorted Lists--python

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.