Leetcode练习(Python):链表类:第21题:合并两个有序链表:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。

题目:
合并两个有序链表:将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
思路:
本题思路较简单。
程序:
# 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
posted on 2020-04-30 23:28  桌子哥  阅读(1588)  评论(0编辑  收藏  举报