Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
Example:
Input: 1->2->4, 1->3->4Output: 1->1->2->3->4->4
这个题目思路就是用dummy node,然后依次判断是l1 小还是l2小,最后当一方是None的时候将另一方加在总list的最后即可。
Code
class ListNode: def __init__(self, x): self.val = x self.next = Noneclass Solution: def mergeTwoLists(self, l1, l2): dummy = ListNode(0) head = dummy while l1 and l2: if l1.val <= l2.val: head.next = l1 l1 = l1.next else: head.next = l2 l2 = l2.next head = head.next head.next = l1 if l1 else l2 return dummy.next