SoFunction
Updated on 2024-11-19

Example of a Python implementation that merges two ordered lists.

This article example describes the Python implementation of merging two ordered linked lists. Shared for your reference, as follows:

reasoning: first elected the first node, and then traversed the two chain tables, the smaller as the next node of the current node, until one of the chain table traversal is complete, at this time the other chain table directly connected to the good

# Definition for singly-linked list.
# class ListNode(object):
#   def __init__(self, x):
#      = x
#      = None
class Solution(object):
  def mergeTwoLists(self, l1, l2):
    """
    :type l1: ListNode
    :type l2: ListNode
    :rtype: ListNode
    """
    # Consider first the case where one of the linked lists is empty
    if not l1:
      return l2
    if not l2:
      return l1
    curNode1 = l1
    curNode2 = l2
    # Pick the first node first
    if  < :
      head = curNode1
      curNode1 = 
    else:
      head = curNode2
      curNode2 = 
    cur = head
    while curNode1 and curNode2:
      if  < :
         = curNode1
        curNode1 = 
      else:
         = curNode2
        curNode2 = 
      cur = 
    # Keep looping until one of the linked lists ends first #
    #If link 1 ends first, the remainder of link 2 is spliced in.
    if not curNode1:
       = curNode2
    #If link 2 ends first, the remainder of link 1 is spliced in.
    else:
       = curNode1
    return head

Readers interested in more Python related content can check out this site's topic: thePython Data Structures and Algorithms Tutorial》、《Summary of Python encryption and decryption algorithms and techniques》、《Summary of Python coding manipulation techniques》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniquesand thePython introductory and advanced classic tutorials

I hope that what I have said in this article will help you in Python programming.