LeetCode23. 合并K个排序链表
/** * 合并K有序链表 ==> 对比归并排序 * * @author Ning */ public class LeetCode23 { public ListNode mergeKLists(ListNode[] lists) { if (lists == null || lists.length == 0) return null; return mergeKLists(lists, 0, lists.length - 1); } private ListNode mergeKLists(ListNode[] lists, int left, int right) { if (left == right) return lists[left]; int mid = (left + right) / 2; ListNode l1 = mergeKLists(lists, left, mid); ListNode l2 = mergeKLists(lists, mid + 1, right); return mergeTwoLists(l1, l2); } public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode dummy = new ListNode(0); ListNode p1 = l1; ListNode p2 = l2; ListNode prev = dummy; while (p1 != null && p2 != null) { if (p1.val <= p2.val) { prev.next = p1; prev = p1; p1 = p1.next; } else { prev.next = p2; prev = p2; p2 = p2.next; } } prev.next = p1 == null ? p2 : p1; return dummy.next; } }
LeetCode148. 排序链表
/** * 排序链表 * @author Ning */ public class LeetCode148 { public ListNode sortList(ListNode head) { if(head == null || head.next == null){ return head; } ListNode slow = head; ListNode fast = head.next; while(fast != null && fast.next != null){ slow = slow.next; fast = fast.next.next; } ListNode temp = slow.next; slow.next = null; ListNode left = sortList(head); ListNode right = sortList(temp); ListNode dummy = new ListNode(0); ListNode pre = dummy; while(left != null && right != null){ if(left.val < right.val){ pre.next = left; left = left.next; }else{ pre.next = right; right = right.next; } pre = pre.next; } pre.next = (left == null ? right : left); return dummy.next; } }