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