/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode sortList(ListNode head) {
//当只有一个元素或者元素为空时不再直接return
if(head == null || head.next == null){
return head;
}
//分割节点
ListNode head1 = head;
ListNode head2 = split(head);
//分割的两个节点排序
head1 = sortList(head1);
head2 = sortList(head2);
return merge(head1,head2);
}
public ListNode split(ListNode head){
//准备好快慢指针
ListNode slow = head;
ListNode fast = head.next;
//循环前进
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
}
//返回第二个链表的头节点
ListNode second = slow.next;
slow.next = null;
return second;
}
public ListNode merge(ListNode head1,ListNode head2){
//哨兵节点
ListNode dummy = new ListNode(0);
ListNode next = dummy;
//排序
while(head1 != null && head2 != null){
if(head1.val < head2.val){
next.next = head1;
head1 = head1.next;
}else{
next.next = head2;
head2 = head2.next;
}
next = next.next;
}
next.next = head1 == null ? head2 : head1;
return dummy.next;
}
}
06-27
311