美文网首页
21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

作者: Chiduru | 来源:发表于2019-03-26 19:04 被阅读0次

【Description】
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

【Idea】

定义两个指针,一个作头指针,另一个作尾指针
对两个链表同时比较头元素,将较小的节点加入新链表中,同时对应链表的头指针后移一位;
最后考虑两个链表不等长,或者其中一个链表有更多小于另一个链表值的节点数量的情况,将剩余未遍历到的子链表直接加入(给定链表分别有序)

【Solution】

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        new_head = ListNode(0)
        prev = new_head
        while l1 and l2:
            if l1.val >= l2.val:
                prev.next = l2
                prev = prev.next
                l2 = l2.next
            elif l2.val > l1.val:
                prev.next = l1
                prev = prev.next
                l1 = l1.next
        if l1:
            prev.next = l1
        if l2:
            prev.next = l2
        return new_head.next

相关文章

网友评论

      本文标题:21. Merge Two Sorted Lists

      本文链接:https://www.haomeiwen.com/subject/febnvqtx.html