示例:
输入:1->3->5,2->5->6
输出:1->2->3->5->5->6
Python解决方案:
# 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 """ prev1 = ListNode(0) prev2 = ListNode(0) prev1.next = l1 prev2.next = l2 head = prev1 while prev1.next and prev2.next: if prev1.next.val <= prev2.next.val: prev1 = prev1.next else: prev1.next,prev2.next = prev2.next,prev1.next prev1 = prev1.next if prev2.next: prev1.next = prev2.next return head.next