python leetcode21 merge two ordered linked lists

Merge two sorted linked lists into a new sorted linked list and return. The new linked list is formed by splicing all the nodes of the given two linked lists. 

Example:

Input: 1->2->4, 1->3->4
 Output: 1->1->2->3->4->4

python code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1 is None:#l1 returns l2 directly when it is empty
            return l2
        if l2 is None:
            return l1
        head=ListNode(0)#Create a new linked list, this is the head node
        current=head
        while l1 is not None and l2 is not None:
            if l1.val<l2.val:
                current.next=l1
                l1=l1.next
            else:
                current.next=l2
                l2=l2.next
            current=current.next
        if l1 is None: #When l1 loops to empty
            current.next=l2
        elif l2 is None:
            current.next=l1
        return head.next####
            
        

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325675753&siteId=291194637