lintcode-medium-Sort List
Posted 哥布林工程师
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了lintcode-medium-Sort List相关的知识,希望对你有一定的参考价值。
Sort a linked list in O(n log n) time using constant space complexity.
Example
Given 1-3->2->null, sort it to 1->2->3->null.
/** * Definition for ListNode. * public class ListNode { * int val; * ListNode next; * ListNode(int val) { * this.val = val; * this.next = null; * } * } */ public class Solution { /** * @param head: The head of linked list. * @return: You should return the head of the sorted linked list, using constant space complexity. */ public ListNode sortList(ListNode head) { // write your code here if(head == null || head.next == null) return head; ListNode slow = head; ListNode fast = head; while(fast != null && fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; } ListNode head2 = slow.next; slow.next = null; head = sortList(head); head2 = sortList(head2); head = merge(head, head2); return head; } public ListNode merge(ListNode head1, ListNode head2){ if(head1 == null) return head2; if(head2 == null) return head1; ListNode fakehead = new ListNode(0); ListNode p = fakehead; ListNode p1 = head1; ListNode p2 = head2; while(p1 != null || p2 != null){ int num1 = Integer.MAX_VALUE; int num2 = Integer.MAX_VALUE; if(p1 != null) num1 = p1.val; if(p2 != null) num2 = p2.val; if(num1 < num2){ p.next = p1; p = p.next; p1 = p1.next; } else{ p.next = p2; p = p.next; p2 = p2.next; } } return fakehead.next; } }
以上是关于lintcode-medium-Sort List的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-medium-Sort Colors II
lintcode-medium-Sort Letters by Case
Java list1=list2;list2=null ? list1=list2;list2.clear()?
Java list1=list2;list2=null ? list1=list2;list2.clear()?