Merge two sorted lists

25 年 6 月 28 日 星期六
123 字
1 分钟

problem

python
# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        cur = dummy = ListNode()
        while list1 and list2:
            if list1.val < list2.val:
                cur.next = list1
                list1 = list1.next
            else:
                cur.next = list2
                list2 = list2.next
            cur = cur.next
        cur.next = list1 or list2 # merge the leftover linklist
        return dummy.next

if list1 or list2 is None, then the leftover must be larger than the tail of new linked list. So we just concatenate the leftovers.

Create a dummy node to contain a new linked list. Then compare the value of two linked lists, to decide the next node.

Remember to connect the leftover list.

文章标题:Merge two sorted lists

文章作者:Sirui Chen

文章链接:https://blog.siruichen.me/posts/21merge_two_sorted_lists[复制]

最后修改时间:


商业转载请联系站长获得授权,非商业转载请注明本文出处及文章链接,您可以自由地在任何媒体以任何形式复制和分发作品,也可以修改和创作,但是分发衍生作品时必须采用相同的许可协议。
本文采用CC BY-NC-SA 4.0进行许可。