leetcode--Sort List

本文介绍了一种使用归并排序思想实现的链表排序算法,该算法可以在O(n log n)的时间复杂度内完成排序,并且仅使用常数级别的额外空间。

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

Sort a linked list in O(n log n) time using constant space complexity.

[java]  view plain  copy
  1. /** 
  2.  * Definition for singly-linked list. 
  3.  * public class ListNode { 
  4.  *     int val; 
  5.  *     ListNode next; 
  6.  *     ListNode(int x) { val = x; } 
  7.  * } 
  8.  */  
  9. public class Solution {  
  10.     public ListNode sortList(ListNode head) {  
  11.         if(head == null || head.next == nullreturn head;  
  12.         ListNode slow = head;  
  13.         ListNode fast = head;  
  14.         while(fast.next != null && fast.next.next != null){  
  15.             slow = slow.next;  
  16.             fast = fast.next.next;  
  17.         }  
  18.         ListNode list2 = slow.next;  
  19.         slow.next = null;  
  20.         head = sortList(head);  
  21.         list2 = sortList(list2);  
  22.         return merge(head, list2);  
  23.     }  
  24.       
  25.     private ListNode merge(ListNode list1, ListNode list2) {  
  26.         if(list1 == nullreturn list2;  
  27.         if(list2 == nullreturn list1;  
  28.         ListNode newHead = new ListNode(0);  
  29.         ListNode last = newHead;  
  30.         last = newHead;  
  31.         while(list1 != null && list2 != null){  
  32.             if(list1.val < list2.val){  
  33.                 last.next = list1;  
  34.                 list1 = list1.next;  
  35.             }else{  
  36.                 last.next = list2;  
  37.                 list2 = list2.next;  
  38.             }  
  39.             last = last.next;  
  40.         }  
  41.         if(list1 != null) last.next = list1;  
  42.         else if(list2 != null) last.next = list2;  
  43.         return newHead.next;  
  44.     }  
  45. }

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/46564321

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值