BM12 单链表的排序
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
public ListNode sortInList (ListNode head)
{
// write code here
// 开始分割
return cut(head);
// 开始合并
}
public ListNode cut(ListNode head)
{
//设置快慢指针
if(head.next == null)
{
return head;
}
ListNode fast = head.next;
ListNode low = head;
//开始遍历
while(fast != null && fast.next != null)
{
fast = fast.next.next;
low = low.next;
}
//low即为中间的结点
ListNode head2 = low.next;
low.next = null;
//现在有两个头结点即为 head和head2
return merge(cut(head),cut(head2));
}
public ListNode merge(ListNode head1,ListNode head2)
{
ListNode dummyNode = new ListNode(-1);
ListNode head = dummyNode;
while(head1 != null && head2 != null)
{
ListNode cur = new ListNode(-1);
if(head1.val <= head2.val)
{
cur = head1;
head1 = head1.next;
}
else{
cur = head2;
head2 = head2.next;
}
cur.next = null;
head.next = cur;
head = head.next;
}
if(head1 != null)
{
head.next = head1;
}
if(head2 != null)
{
head.next = head2;
}
return dummyNode.next;
}
}