題目:
合並兩個有序鏈表:將兩個升序鏈表合並為一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。
思路:
本題思路較簡單。
程序:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
if not l1 and not l2:
return None
if not l1 and l2:
return l2
if l1 and not l2:
return l1
headForList = ListNode(0)
myListNode = headForList
while l1 and l2:
if l1.val <= l2.val:
myListNode.next = l1
l1 = l1.next
else:
myListNode.next = l2
l2 = l2.next
myListNode = myListNode.next
if l1:
myListNode.next = l1
else:
myListNode.next = l2
return headForList.next