# sort-list（Leetcode）

## 题目描述

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;
}
}
• 本文已收录于以下专栏：

举报原因： 您举报文章：sort-list（Leetcode） 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)