【重点】【归并排序】148.排序链表

合并有序链表的多种算法实现
文章介绍了四种方法来合并两个已排序的链表,包括归并排序的自上而下和自底向上策略,优先队列以及修改节点值的方法。

题目
基础题目:
21. 合并两个有序链表
876. 链表的中间结点

法1:归并排序,自上而下

基本好法,必须掌握!
时间复杂度:O(nlgn)

Python

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head
        slow, fast = head, head
        pre = None # slow的前序节点
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        l1 = self.sortList(head)
        l2 = self.sortList(slow)

        return self.merge(l1, l2)
    
    def merge(self, l1, l2):
        dummy = ListNode(-1)
        cur, cur1, cur2 = dummy, l1, l2
        while cur1 and cur2:
            if cur1.val <= cur2.val:
                cur.next = cur1
                cur1 = cur1.next
            else:
                cur.next = cur2
                cur2 = cur2.next   
            cur = cur.next
        cur.next = cur1 if cur1 else cur2
        return dummy.next

Java

class Solution {
   
   
    public ListNode sortList(ListNode head) {
   
   
        if (head == null || head.next == null) {
   
   
            return head;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值