Leetcode 148 Sort List

来源:互联网 发布:ubuntu 卸载fcitx 编辑:程序博客网 时间:2024/06/06 10:53

Sort a linked list in O(n log n) time using constant space complexity.

第一反应就是merge 或者 quicksort

先来merge的。。quicksort待我写好加上

/** * 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){            return null;        }                if(head.next == null){            return head;        }                 ListNode runner = head;         ListNode walker = head;         ListNode prev = null;        while(runner != null && runner.next != null){            prev = walker;            runner = runner.next.next;            walker = walker.next;        }              prev.next = null;       ListNode left = sortList(head);       ListNode right = sortList(walker);              return merge(left,right);                         }        private ListNode merge(ListNode left, ListNode right){         ListNode head = new ListNode(0), p = head;        while(left != null && right != null){            if(left.val < right.val){                p.next = left;                left = left.next;            }else{                p.next = right;                right = right.next;            }            p = p.next;        }        if(left != null){            p.next = left;        }                if(right != null){            p.next = right;        }        return head.next;    }           }


0 0