给一个无序的链表排序
//找链表的中间节点
public Node getmiddle(List l){
if(l == null){
return l;
}
Node fast = l;
Node slow = l;
//快指针走2步,慢指针走1步,快指针走到结尾时,慢指针刚好走到中间节点
while(fast != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
}
return slow;
}
//排序、合并链表
public Node merge(Node left,Node right){
Node tmp = new Node(0);
Node thead = tmp;
//从前向后遍历左右两部分链表,并进行排序合并
while(left != null && right != null){
if(left.value < right.value){
thead.next = left;
left = left.next;
}else{
thead.next = right;
right = right.next;
}
//如果左半部分还有剩余,将其链接到链表最后
while(left != null){
thead.next = left;
}
//如果右半部分还有剩余,将其链接到链表最后
while(right != null){
tmp.head = right;
}
return tmp.next;
}
}
public void sortlist(List l){
//找链表的中间节点
Node mid = getmiddle(l);
//将链表分开前后2部分
Node right = mid.next;
mid.next = null;
//合并前后2部分的结果
return merge(sortlist(l),sortlist(right));
}