148. Sort List
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 dummy = head; ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null){ dummy = slow; slow = slow.next; fast = fast.next.next; } dummy.next = null; // 断开 两条list ListNode l1 = sortList(head); ListNode l2 = sortList(slow); return mergeLists(l1,l2); } public ListNode mergeLists(ListNode l1, ListNode l2){ if(l1 == null && l2 == null) return null; if(l1 == null) return l2; if(l2 == null) return l1; if(l1.val > l2.val){ l2.next = mergeLists(l1, l2.next); return l2; } else{ l1.next = mergeLists(l1.next, l2); return l1; } } }
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步