在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
if(head == null) return null;
List<Integer> val_list = new ArrayList<>();
ListNode temp = head;
while(temp != null) {
val_list.add(temp.val);
temp = temp.next;
}
val_list.sort(Integer::compareTo);
MyList(val_list.toArray(new Integer[val_list.size()]));
return root;
}
public ListNode root;
public void MyList(Integer[] nodeList) {
int nodeList_len = nodeList.length;
if(nodeList_len == 0) root = null;
else {
// 创建节点
root = new ListNode(nodeList[0]);
ListNode temp_node = root;
for(int i = 1; i < nodeList_len; i++) {
temp_node.next = new ListNode(nodeList[i]);
temp_node = temp_node.next;
}
}
}
}
快慢指针
// Others
public class Solution {
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
// step1. cut the list two halves
ListNode prev = null, slow = head, fast = head;
while(fast != null && fast.next != null) {
prev = slow;
slow = slow.next;
fast = fast.next.next;
}
prev.next = null;
// step2. sort each half
ListNode l1 = sortList(head);
ListNode l2 = sortList(slow);
// step3. merge l1 and l2
return merge(l1, l2);
}
ListNode merge(ListNode l1, ListNode l2) {
ListNode l = new ListNode(0), p = l;
while(l1 != null && l2 != null) {
if(l1.val < l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
}
if(l1 != null) p.next = l1;
if(l2 != null) p.next = l2;
return l.next;
}
}