Python解决链表合并和排序问题

将两个链表合并后再排序

链表定义:

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

将列表转化为链表:

def create_linked_list(lst):
    dummy = ListNode()  # 创建一个虚拟头节点
    current = dummy  # 设置当前节点为虚拟头节点
    for number in lst:  # 遍历输入的列表
        current.next = ListNode(number)  # 创建新节点,连接到当前节点的后面
        current = current.next  # 将当前节点指针移动到下一个节点
    return dummy.next  # 返回虚拟头节点的下一个节点,即实际的链表头

合并并排序的方法:

class Solution1:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        if l1==None and l2==None:
            return None
        if l1==None:
            return l2
        if l2==None:
            return l1
        if l1.val<=l2.val:
            l1.next=self.mergeTwoLists(l1.next,l2)
            return l1
        else:
            l2.next=self.mergeTwoLists(l1,l2.next)
            return l2
class Solution2:
    def mergeTwoLists(self, l1, l2):
        """
        :type l1: ListNode
        :type l2: ListNode
        :rtype: ListNode
        """
        head = ListNode(0)
        first = head
        while l1 != None and l2 != None:
            if l1.val > l2.val:
                head.next = l2
                l2 = l2.next
            else :
                head.next = l1
                l1 = l1.next
            head = head.next
        if l1 == None:
            head.next = l2
        elif l2 == None:
            head.next = l1
        return first.next

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值