1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
| class Solution { public ListNode sortList(ListNode head) { return sortList(head, null); }
public ListNode sortList(ListNode head, ListNode tail){ if(head == null) return head; if(head.next == tail){ head.next = null; return head; } ListNode slow = head, fast = head; while(fast != tail){ slow = slow.next; fast = fast.next; if(fast != tail){ fast = fast.next; } } ListNode mid = slow; ListNode list1 = sortList(head, mid); ListNode list2 = sortList(mid, tail); ListNode sorted = mergeTwoList(list1, list2); return sorted; }
public ListNode mergeTwoList(ListNode p1, ListNode p2){ ListNode dummyNode = new ListNode(0); ListNode temp = dummyNode, temp1 = p1, temp2 = p2; while(temp1 != null && temp2 != null){ if(temp1.val <= temp2.val){ temp.next = temp1; temp1 = temp1.next; }else{ temp.next = temp2; temp2 = temp2.next; } temp = temp.next; } if(temp1 != null){ temp.next = temp1; }else if(temp2 != null){ temp.next = temp2; } return dummyNode.next; } }
class Solution { public ListNode sortList(ListNode head) { if(head == null) return head; int length = 0; ListNode node = head; while(node != null){ length++; node = node.next; } ListNode dummyNode = new ListNode(0); dummyNode.next = head;
for(int sublen = 1; sublen < length; sublen <<= 1){ ListNode pre = dummyNode; ListNode cur = dummyNode.next; while(cur != null){ ListNode head_1 = cur; for(int i = 1; i < sublen && cur != null && cur.next != null; i++){ cur = cur.next; }
ListNode head_2 = cur.next; cur.next = null; cur = head_2; for(int i = 1; i < sublen && cur != null && cur.next != null; i++){ cur = cur.next; }
ListNode next = null; if(cur != null){ next = cur.next; cur.next = null; }
ListNode merged = mergeTwoList(head_1, head_2); pre.next = merged; while(pre.next != null){ pre = pre.next; } cur = next; } } return dummyNode.next; }
public ListNode mergeTwoList(ListNode p1, ListNode p2){ ListNode dummyNode = new ListNode(0); ListNode temp = dummyNode, temp1 = p1, temp2 = p2; while(temp1 != null && temp2 != null){ if(temp1.val <= temp2.val){ temp.next = temp1; temp1 = temp1.next; }else{ temp.next = temp2; temp2 = temp2.next; } temp = temp.next; } if(temp1 != null){ temp.next = temp1; }else if(temp2 != null){ temp.next = temp2; } return dummyNode.next; } }
|