首页 > 代码库 > Sort List
Sort List
Sort List
Sort a linked list in O(n log n) time using constant space complexity.
答案
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */ public class Solution { public ListNode sortList(ListNode head) { if (head == null || head.next == null) return head; int LEN = 0; ListNode p = head; while (p != null) { LEN++ ; p = p.next; } ListNode pFirstHead, pFirstEnd, pSecondHead; int i; for (i = 1, pFirstEnd = head; i < LEN / 2; i++ ) pFirstEnd = pFirstEnd.next; pSecondHead = pFirstEnd.next; pFirstEnd.next = null; pFirstHead = sortList(head); pSecondHead = sortList(pSecondHead); head = null; for (; pFirstHead != null && pSecondHead != null;) { ListNode smallNode; if (pFirstHead.val < pSecondHead.val) { smallNode = pFirstHead; pFirstHead = pFirstHead.next; } else { smallNode = pSecondHead; pSecondHead = pSecondHead.next; } smallNode.next = null; if (head == null) { head = smallNode; p = head; } else { p.next = smallNode; p = smallNode; } } if (pFirstHead != null) p.next = pFirstHead; else { p.next = pSecondHead; } return head; } }
Sort List
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。