【code-021】MergeTwoSortedList

1. 问题描述


2. 解决办法:

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

class Solution(object):
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        dummy_head = ListNode(0)
        current = dummy_head
        while l1 and l2:
            if l1.val <= l2.val:
                current.next = ListNode(l1.val)
                l1 = l1.next
            else:
                current.next = ListNode(l2.val)
                l2 = l2.next
            current = current.next
        # while l1:
        #     current.next = ListNode(l1.val)
        #     l1 = l1.next
        #     current = current.next
        # while l2:
        #     current.next = ListNode(l2.val)
        #     l2 = l2.next
        #     current = current.next
        current.next = l1 or l2
        return dummy_head.next

l2 = ListNode(5)
l22 = ListNode(6)
l23 = ListNode(4)
l2.next = l22
l22.next = l23
s = Solution()
a = s.mergeTwoLists(l2, l2)
print(a)

3. 个人记录:
1.这道题和求两个sortedList的中位数的那道题很像
2. 关于链表,几个注意的点:
要有一个变量不断记录当前节点
current.next=ListNode(l1.val)

猜你喜欢

转载自blog.csdn.net/zhangjipinggom/article/details/85178189