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
| package com.demo.s147;
class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } ListNode(int val, ListNode next) { this.val = val; this.next = next; } } public 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 fast = head; ListNode slow = head; while(fast != tail) { fast = fast.next; slow = slow.next; if(fast != tail) { fast = fast.next; } } ListNode mid = slow; ListNode m = sortList(head, mid); ListNode n = sortList(mid, tail); return mergeList(m, n); } public ListNode mergeList(ListNode head, ListNode tail) { ListNode dum = new ListNode(0); ListNode tmp1 = head; ListNode tmp2 = tail; ListNode tmp = dum; while(tmp1 != null && tmp2 != null) { if(tmp1.val < tmp2.val) { tmp.next = tmp1; tmp1 = tmp1.next; } else { tmp.next = tmp2; tmp2 = tmp2.next; } tmp = tmp.next; } if(tmp1 != null) { tmp.next = tmp1; } if(tmp2 != null) { tmp.next = tmp2; } return dum.next; }
}
|