对一个链表进行排序
Input: 4->2->1->3
Output: 1->2->3->4
Input: -1->5->3->4->0
Output: -1->0->3->4->5
public ListNode sortList(ListNode head) {
if(head == null || head.next == null) return head;
ListNode slow = head,fast = head,pre = null;
//将链表分为两部分
while(fast != null && fast.next != null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
ListNode l1 = sortList(head); //左边向下拆分
ListNode l2 = sortList(slow); //右边向下拆分
return merge(l1, l2); //拼接节点
}
private ListNode merge(ListNode node1,ListNode node2){
ListNode node = new ListNode(-1);
ListNode head = node;
while(node1 != null && node2 != null){
if(node1.val < node2.val){
head.next = node1;
node1 = node1.next;
}else{
head.next = node2;
node2 = node2.next;
}
head = head.next;
}
if(node1 != null){
head.next = node1;
}
if(node2 != null){
head.next = node2;
}
return node.next;
}
原文:https://www.cnblogs.com/le-le/p/12885384.html