148. Sort List
2017-03-02 19:37
92 查看
Sort a linked list in O(n log n) time using constant space complexity.
归并
快排
归并
/** * 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 || head.next == null) return head; // get mid ListNode mid = getmid(head); //sort ListNode tmp = mid.next; mid.next = null; ListNode midleft = sortList(head); ListNode midright = sortList(tmp); //merge return merge(midleft, midright); } public ListNode getmid(ListNode head) { ListNode fast = head.next; ListNode slow = head; while (fast != null && fast.next != null) { fast = fast.next.next; slow = slow.next; } return slow; } public ListNode merge(ListNode midleft, ListNode midright) { ListNode dummy = new ListNode(0); ListNode node = dummy; while (midleft != null && midright != null) { if (midleft.val < midright.val) { node.next = midleft; node = node.next; midleft = midleft.next; } else { node.next = midright; node = node.next; midright = midright.next; } } if(midleft != null) node.next = midleft; if(midright != null) node.next = midright; return dummy.next; } }
快排
/** * 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 || head.next == null) return head; //pivot ListNode pivot = head; head = head.next; pivot.next = null; ListNode p = pivot; //small, large ListNode small = new ListNode(0); ListNode large = new ListNode(0); ListNode s = small; ListNode l = large; while (head != null) { if (head.val < pivot.val) { s.next = head; head = head.next; s = s.next; } else if (head.val == pivot.val) { p.next = head; head = head.next; p = p.next; } else { l.next = head; head = head.next; l = l.next; } } //merge s.next = null; l.next = null; ListNode res = sortList(small.next); if (res == null) res = pivot; else { ListNode tmp = res; while (tmp.next != null) tmp = tmp.next; tmp.next = pivot; } p.next = sortList(large.next); return res; } }
相关文章推荐
- LeetCode 148. Sort List--O(nlogn)时间复杂度和常数空间复杂度给链表排序
- [LeetCode] 148. Sort List 链表排序
- leetcode 148. Sort List
- [LeetCode] 148. Sort List
- 【C++】【LeetCode】148. Sort List
- 148. Sort List (python)
- 148. Sort List (归并) 和147. Insertion Sort List
- 148. Sort List
- 148. Sort List -- 时间复杂度O(n log n)
- 148. Sort List--单链表自底向上归并排序
- 148. Sort List
- LeetCode 148. Sort List
- 148. Sort List(unsolved)
- 148. Sort List
- LeetCode 148. Sort List(C++版)
- Leetcode 148. Sort List
- 148. Sort List
- 148. Sort List
- 148. Sort List --- leetcode
- LeetCode - 148. Sort List