剑指 Offer II 077. 链表排序


comments: true
edit_url: https://github.com/doocs/leetcode/edit/main/lcof2/%E5%89%91%E6%8C%87%20Offer%20II%20077.%20%E9%93%BE%E8%A1%A8%E6%8E%92%E5%BA%8F/README.md

剑指 Offer II 077. 链表排序

题目描述

给定链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表

     

    示例 1:

    输入:head = [4,2,1,3]
    输出:[1,2,3,4]
    

    示例 2:

    输入:head = [-1,5,3,4,0]
    输出:[-1,0,3,4,5]
    

    示例 3:

    输入:head = []
    输出:[]
    

     

    提示:

    • 链表中节点的数目在范围 [0, 5 * 104] 内
    • -105 <= Node.val <= 105

     

    进阶:你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?

     

    注意:本题与主站 148 题相同:https://leetcode.cn/problems/sort-list/

    解法

    方法一

    Python3
    # 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: ListNode) -> ListNode:
            if not head or not head.next:return head
    
            # 归 划分
            slow,fast=head,head.next
            while fast and fast.next:
                slow,fast=slow.next,fast.next.next
            l=head
            r=slow.next
            slow.next=None
            left=self.sortList(l)
            right=self.sortList(r)
    
            # 并排序
            return self.merge(left,right)
    
        def merge(self,left,right):
            dummy=ListNode()
            cur=dummy
            while left and right:
                if left.val<=right.val:
                    cur.next=left
                    left=left.next
                else:
                    cur.next=right
                    right=right.next
                cur=cur.next # 遗忘
            cur.next= left if not right else right
            return dummy.next
    
    Java
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode() {}
     *     ListNode(int val) { this.val = val; }
     *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     * }
     */
    class Solution {
        public ListNode sortList(ListNode head) {
            if (head == null || head.next == null) {
                return head;
            }
            ListNode slow = head, fast = head.next;
            while (fast != null && fast.next != null) {
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode t = slow.next;
            slow.next = null;
            ListNode l1 = sortList(head);
            ListNode l2 = sortList(t);
            ListNode dummy = new ListNode();
            ListNode cur = dummy;
            while (l1 != null && l2 != null) {
                if (l1.val <= l2.val) {
                    cur.next = l1;
                    l1 = l1.next;
                } else {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
            cur.next = l1 == null ? l2 : l1;
            return dummy.next;
        }
    }
    
    C++
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode() : val(0), next(nullptr) {}
     *     ListNode(int x) : val(x), next(nullptr) {}
     *     ListNode(int x, ListNode *next) : val(x), next(next) {}
     * };
     */
    class Solution {
    public:
        ListNode* sortList(ListNode* head) {
            if (!head || !head->next) return head;
            auto* slow = head;
            auto* fast = head->next;
            while (fast && fast->next) {
                slow = slow->next;
                fast = fast->next->next;
            }
            auto* t = slow->next;
            slow->next = nullptr;
            auto* l1 = sortList(head);
            auto* l2 = sortList(t);
            auto* dummy = new ListNode();
            auto* cur = dummy;
            while (l1 && l2) {
                if (l1->val <= l2->val) {
                    cur->next = l1;
                    l1 = l1->next;
                } else {
                    cur->next = l2;
                    l2 = l2->next;
                }
                cur = cur->next;
            }
            cur->next = l1 ? l1 : l2;
            return dummy->next;
        }
    };
    
    Go
    /**
     * Definition for singly-linked list.
     * type ListNode struct {
     *     Val int
     *     Next *ListNode
     * }
     */
    func sortList(head *ListNode) *ListNode {
    	if head == nil || head.Next == nil {
    		return head
    	}
    	slow, fast := head, head.Next
    	for fast != nil && fast.Next != nil {
    		slow, fast = slow.Next, fast.Next.Next
    	}
    	t := slow.Next
    	slow.Next = nil
    	l1, l2 := sortList(head), sortList(t)
    	dummy := &ListNode{}
    	cur := dummy
    	for l1 != nil && l2 != nil {
    		if l1.Val <= l2.Val {
    			cur.Next = l1
    			l1 = l1.Next
    		} else {
    			cur.Next = l2
    			l2 = l2.Next
    		}
    		cur = cur.Next
    	}
    	if l1 != nil {
    		cur.Next = l1
    	} else {
    		cur.Next = l2
    	}
    	return dummy.Next
    }
    
    TypeScript
    /**
     * Definition for singly-linked list.
     * class ListNode {
     *     val: number
     *     next: ListNode | null
     *     constructor(val?: number, next?: ListNode | null) {
     *         this.val = (val===undefined ? 0 : val)
     *         this.next = (next===undefined ? null : next)
     *     }
     * }
     */
    
    function sortList(head: ListNode | null): ListNode | null {
        if (head == null || head.next == null) return head;
        // 快慢指针定位中点
        let slow: ListNode = head,
            fast: ListNode = head.next;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
        }
        // 归并排序
        let mid: ListNode = slow.next;
        slow.next = null;
        let l1: ListNode = sortList(head);
        let l2: ListNode = sortList(mid);
        let dummy: ListNode = new ListNode();
        let cur: ListNode = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 == null ? l2 : l1;
        return dummy.next;
    }
    
    JavaScript
    /**
     * Definition for singly-linked list.
     * function ListNode(val, next) {
     *     this.val = (val===undefined ? 0 : val)
     *     this.next = (next===undefined ? null : next)
     * }
     */
    /**
     * @param {ListNode} head
     * @return {ListNode}
     */
    var sortList = function (head) {
        if (!head || !head.next) {
            return head;
        }
        let slow = head;
        let fast = head.next;
        while (fast && fast.next) {
            slow = slow.next;
            fast = fast.next.next;
        }
        let t = slow.next;
        slow.next = null;
        let l1 = sortList(head);
        let l2 = sortList(t);
        const dummy = new ListNode();
        let cur = dummy;
        while (l1 && l2) {
            if (l1.val <= l2.val) {
                cur.next = l1;
                l1 = l1.next;
            } else {
                cur.next = l2;
                l2 = l2.next;
            }
            cur = cur.next;
        }
        cur.next = l1 || l2;
        return dummy.next;
    };
    
    C#
    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     public int val;
     *     public ListNode next;
     *     public ListNode(int val=0, ListNode next=null) {
     *         this.val = val;
     *         this.next = next;
     *     }
     * }
     */
    public class Solution {
        public ListNode SortList(ListNode head) {
            if (head == null || head.next == null)
            {
                return head;
            }
            ListNode slow = head, fast = head.next;
            while (fast != null && fast.next != null)
            {
                slow = slow.next;
                fast = fast.next.next;
            }
            ListNode t = slow.next;
            slow.next = null;
            ListNode l1 = SortList(head);
            ListNode l2 = SortList(t);
            ListNode dummy = new ListNode();
            ListNode cur = dummy;
            while (l1 != null && l2 != null)
            {
                if (l1.val <= l2.val)
                {
                    cur.next = l1;
                    l1 = l1.next;
                }
                else
                {
                    cur.next = l2;
                    l2 = l2.next;
                }
                cur = cur.next;
            }
            cur.next = l1 == null ? l2 : l1;
            return dummy.next;
        }
    }
    
    Swift
    
    /** class ListNode {
    *    var val: Int
    *    var next: ListNode?
    *    init() { self.val = 0; self.next = nil }
    *    init(_ val: Int) { self.val = val; self.next = nil }
    *    init(_ val: Int, _ next: ListNode?) { self.val = val; self.next = next }
    * }
    */
    
    class Solution {
        func sortList(_ head: ListNode?) -> ListNode? {
            guard let head = head, head.next != nil else {
                return head
            }
    
            var slow: ListNode? = head
            var fast: ListNode? = head.next
    
            while fast != nil && fast?.next != nil {
                slow = slow?.next
                fast = fast?.next?.next
            }
    
            let mid = slow?.next
            slow?.next = nil
    
            let left = sortList(head)
            let right = sortList(mid)
    
            return merge(left, right)
        }
    
        private func merge(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
            let dummy = ListNode()
            var cur = dummy
            var l1 = l1, l2 = l2
    
            while let node1 = l1, let node2 = l2 {
                if node1.val <= node2.val {
                    cur.next = node1
                    l1 = node1.next
                } else {
                    cur.next = node2
                    l2 = node2.next
                }
                cur = cur.next!
            }
    
            cur.next = l1 ?? l2
            return dummy.next
        }
    }
    
    评论
    添加红包

    请填写红包祝福语或标题

    红包个数最小为10个

    红包金额最低5元

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

    抵扣说明:

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

    余额充值