leetcode--Sort List

本文详细介绍了如何使用常空间复杂度实现链表排序算法,达到O(nlogn)的时间复杂度。通过合并两个已排序的部分,实现了高效且内存友好的链表排序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Sort a linked list in O(n log n) time using constant space complexity.
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
	    if(head == null || head.next == null) return head;
		ListNode slow = head;
		ListNode fast = head;
	    while(fast.next != null && fast.next.next != null){
	    	slow = slow.next;
	    	fast = fast.next.next;
	    }
	    ListNode list2 = slow.next;
	    slow.next = null;
	    head = sortList(head);
	    list2 = sortList(list2);
    	return merge(head, list2);
	}
	
	private ListNode merge(ListNode list1, ListNode list2) {
		if(list1 == null) return list2;
		if(list2 == null) return list1;
		ListNode newHead = new ListNode(0);
		ListNode last = newHead;
		last = newHead;
		while(list1 != null && list2 != null){
			if(list1.val < list2.val){
				last.next = list1;
				list1 = list1.next;
			}else{
				last.next = list2;
				list2 = list2.next;
			}
			last = last.next;
		}
		if(list1 != null) last.next = list1;
		else if(list2 != null) last.next = list2;
		return newHead.next;
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值