LeetCode:21. Merge Two Sorted Lists

博客围绕LeetCode 21题合并两个有序链表展开。思路是同时遍历两个链表,将val值小的节点插入新链表,一个链表遍历完后,把另一个剩余链表合并到新链表,还给出了Python代码实现。

LeetCode:21. Merge Two Sorted Lists

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

合并两个有序链表

思路

同时遍历两个链表,val值小的插入到新的链表,知道有个链表遍历结束,再把剩余的那个链表合并到新链表。

Python 代码实现

# 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:
        head1,head2 = l1,l2
        newl = ListNode(0)
        newhead = newl
        while (head1 is not None and head2 is not None):
            if head1.val <= head2.val:
                tmp = ListNode(head1.val)
                newhead.next = tmp
                newhead = newhead.next
                head1 = head1.next
            elif head2.val <= head1.val:
                tmp = ListNode(head2.val)
                newhead.next = tmp
                newhead = newhead.next
                head2 = head2.next
                
        if head1 is not None:
            newhead.next = head1
                
        if head2 is not None:
            newhead.next = head2
        
        return newl.next

THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值