leetcode之时间复杂度为O(nlogn)的链表排序

来源:互联网 发布:数据分析的网站有哪些 编辑:程序博客网 时间:2024/05/20 16:35

3. Sort List

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

使用归并排序的思想,代码如下:

/** * Sort a linked list in O(n log n) time using constant space complexity. */package com.leetcode.program;import java.util.Random;public class SortLinkedList {public ListNode sortList(ListNode head){if(head == null || head.next == null)return head;ListNode midNode = findMiddleNode(head);if(midNode == null)return null;ListNode mid = midNode.next;midNode.next = null;ListNode h1 = sortList(head);ListNode h2 = sortList(mid);return mergeListNode(h1, h2);//return null;}private ListNode mergeListNode(ListNode h1, ListNode h2){ListNode hret = (h1 == null) ? h2 : h1;if(hret == null)return hret;hret = (h1.val < h2.val) ? h1 : h2;if(hret == h1)h1 = h1.next;elseh2 = h2.next;ListNode lashRet = hret;//the lash node of the returned Listwhile(h1 != null && h2 != null){if(h1.val < h2.val){lashRet.next = h1;lashRet = h1;h1 = h1.next;}else{lashRet.next = h2;lashRet = h2;h2 = h2.next;}}if(h1 != null)lashRet.next = h1;if(h2 != null)lashRet.next = h2;return hret;}/*寻找链表的中间节点*/private ListNode findMiddleNode(ListNode h){if(null == h || h.next == null)return h;ListNode midNode = h;while(h != null && h.next != null && h.next.next != null){h = h.next.next;midNode = midNode.next;}return midNode;}public static void main(String[] args) {Random rand = new Random();ListNode head = null;ListNode currentNode = null;for(int i = 0 ; i < 10; i ++){if(head == null){head = new ListNode(rand.nextInt(47));currentNode = head;}else{currentNode.next = new ListNode(rand.nextInt(47));currentNode = currentNode.next;}}SortLinkedList s = new SortLinkedList();ListNode mid = s.findMiddleNode(head);System.out.println(mid.val);ListNode hret = s.sortList(head);while(hret != null){System.out.print(hret.val + " ");hret = hret.next;}//while(head != null)//{//System.out.print(head.val + " ");//head = head.next;//}}}class ListNode{int val;ListNode next;ListNode(int x){val = x;next = null;}}

0 0
原创粉丝点击