problem address
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->4 Output: 1->1->2->3->4->4我们可以让两个指针i,j分别指向了两个链表的头结点然后比较值,然后++ 操作, 最后还可能有剩余的链表节点没有合并,合并返回头结点即可。
# 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: root = ListNode(None) cur = root while l1 and l2: if l1.val < l2.val: node = ListNode(l1.val) l1 = l1.next else: node = ListNode(l2.val) l2 = l2.next cur.next = node cur = node cur.next = l1 or l2 return root.next