# sort-list（Leetcode）

96人阅读 评论(0)

## 题目描述

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

package sxd.learn.java.leetcode;

/**
*
* @author lab
* 2016/5/24
* sort-list : Sort a linked list in O(n log n) time using
*         constant space complexity.
*/
public class Leetcode4 {

public static void main(String[] args) {

}

int size = 0;
while (current != null) {
size++;
current = current.next;
}

int mid_size = (size - 1) / 2;
for (int i = 1; i <= mid_size; i++)
mid = mid.next;
mid.next = null;
ListNode result = merge(h1, h2);

return result;
}

public ListNode merge(ListNode h1, ListNode h2) {
if (h1 == null)
return h2;
if (h2 == null)
return h1;

ListNode head, cur, h1_cur = h1, h2_cur = h2;
if (h1_cur.val < h2_cur.val) {
h1_cur = h1_cur.next;
} else {
h2_cur = h2_cur.next;
}

while (h1_cur != null && h2_cur != null) {
if (h1_cur.val < h2_cur.val) {
cur.next = h1_cur;
h1_cur = h1_cur.next;
} else {
cur.next = h2_cur;
h2_cur = h2_cur.next;
}
cur = cur.next;
}
if (h1_cur != null)
cur.next = h1_cur;
if (h2_cur != null)
cur.next = h2_cur;

}

}

class ListNode {
int val;
ListNode next;

ListNode(int x) {
val = x;
next = null;
}
}
0
0

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
个人资料
• 访问：14508次
• 积分：720
• 等级：
• 排名：千里之外
• 原创：57篇
• 转载：8篇
• 译文：1篇
• 评论：0条
文章分类