Sort a linked list in O(n log n) time using constant space complexity. Keys for solving the problem Break the list to two in the middle Recursively sort the two sub lists Merge the two sub lists This is my accepted answer for the problem. package algorithm.sort; class ListNode { int val; ListNode next; ListNode(int x) { val = x; next = null; } } public class SortLinkedList { // merge sort public static ListNode mergeSortList(ListNode head) { if (head == null || head.next == null) return head; // count total number of elements int count = 0; ListNode p = head; while (p !
Read full article from LeetCode Solution – Merge Sort LinkedList in Java
No comments:
Post a Comment