本文共 877 字,大约阅读时间需要 2 分钟。
class ListNode:
def init(self, x):self.val = xself.next = Noneclass Solution:def mergeTwoLists(self, l1, l2):""":type l1: ListNode:type l2: ListNode:rtype: ListNode"""head = ListNode(0) first = head while l1!=None and l2!=None: if l1.val <= l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next if l1 != None: head.next = l1 elif l2 != None: head.next = l2 return first.next
head1 = ListNode(1)
n1 = ListNode(2)n2 = ListNode(4)n3 = ListNode(5)head1.next = n1n1.next = n2n2.next = n3head2 = ListNode(1)
m1 = ListNode(2)m2 = ListNode(3)m3 = ListNode(8)head2.next = m1m1.next = m2m2.next = m3s = Solution()
res = s.mergeTwoLists(head1,head2)while res:print(res.val)res = res.next转载于:https://blog.51cto.com/13930723/2311551