leecode——merge two sorted linked list(21)

做链表相关的题的工具类和方法:
ListNode是链表的一个节点
array_to_list:把一个array转化为链表
print_list:打印一个链表

# -*- coding:utf-8 -*-


class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


def array_to_list(array: list) -> ListNode:
    """
    transform an array to linked list
    :param array: 
    :return: the head of the linked list.
    """
    
    if len(array) == 0:
        return None
    cur = dummy = ListNode(None)
    for i in range(len(array)):
        cur.next = ListNode(array[i])
        cur = cur.next
    return dummy.next


def print_list(head: ListNode) -> None:
    """
    print a linked list
    :param head: 
    :return: 
    """
    if not head:
        return

    ret = ''
    while head:
        if not ret:
            ret = str(head.val)
        else:
            ret = ret + '->' + str(head.val)
        head = head.next

    print(ret + '->None')

在这里插入图片描述

def mergeTwoLists(l1: ListNode, l2: ListNode) -> ListNode:
    """
    循环的方法:
    用了四个指针,一个是dummy,用来标记新list的开头的,cur是新list的指针,
    l1, l2 分别是两个List是头指针;
    cur指针与l1,l2指针是会移动的。
    :param l1:
    :param l2:
    :return:
    """
    dummy = cur = ListNode(None)
    while l1 and l2:  # l1,l2都不能为None,如果有一个为None跳出while
        if l1.val < l2.val:
            cur.next = l1
            l1 = l1.next
        else:
            cur.next = l2
            l2 = l2.next

        cur = cur.next
    cur.next = l1 or l2  # l1 and l2 which one is not None, the one is result
    return dummy.next
def mergeTwoLists2(l1: ListNode, l2: ListNode) -> ListNode:
    """
    递归的方法
    :param l1:
    :param l2:
    :return:
    """
    if not l1 or not l2:
        return l1 or l2

    if l1.val < l2.val:
        l1.next = mergeTwoLists2(l1.next, l2)
        return l1
    else:
        l2.next = mergeTwoLists2(l1, l2.next)
        return l2
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值