首页 > 代码库 > 148. Sort List
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; } } }
148. Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。