Sort a linked list in O(n log n) time using constant space complexity.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
对链表进行归并排序
递归找到链表的中间节点,并划分为两段链表。对划分的两段链表合并
1、获取链表的中间节点
可以通过一个指针每次前进一个节点,另一个指针每次前进两个节点
public ListNode getMiddle(ListNode head){
ListNode p1=head;
ListNode p2=head;
while(p2.next!=null&&p2.next.next!=null){
p1=p1.next;
p2=p2.next.next;
}
return p1;
}
2、合并两段链表
public ListNode merge(ListNode a,ListNode b){
ListNode res=new ListNode(-1);
ListNode cur=res;
while(a!=null&&b!=null){
if(a.val<b.val){
cur.next=a;
a=a.next;
}
else{
cur.next=b;
b=b.next;
}
cur=cur.next;
}
if(a!=null)
cur.next=a;
else if(b!=null)
cur.next=b;
return res.next;
}
3、归并排序
public ListNode sortList(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode middle=getMiddle(head);
ListNode next=middle.next;
middle.next=null; //分隔链表为两段链表
return merge(sortList(head),sortList(next)); //递归
}