package demo8;
/**
* @author xianyu
* @version 1.0
* @date 2020/4/20 12:11
* 单链表的归并排序
*/
public class mergeSort {
public static void main(String[] args) {
Node head = new Node(7);
head.next = new Node(5);
head.next.next = new Node(3);
head.next.next.next = new Node(1);
head.next.next.next.next = new Node(12);
head.toPrint();
mergeSort(head).toPrint();
}
public static Node mergeSort(Node head){
if(head==null || head.next==null) return head;
Node midHead = findMidHead(head);
return merge(mergeSort(head),mergeSort(midHead));
}
public static Node merge(Node p1,Node p2){
Node dummy = new Node(-1);
Node p = dummy;
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
p.next = p1;
p1 = p1.next;
}else{
p.next = p2;
p2 = p2.next;
}
p = p.next;
}
if(p1!=null){
p.next = p1;
}
if(p2!=null){
p.next = p2;
}
return dummy.next;
}
public static Node findMidHead(Node head){
Node fast = head;
Node slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
}
Node midHead = slow.next;
slow.next = null;
return midHead;
}
static class Node{
int val;
Node next;
public Node(int val){
this.val = val;
}
public void toPrint(){
Node p = this;
while( p!=null ){
System.out.print(p.val + " ");
p = p.next;
}
System.out.println();
}
}
}
单链表归并排序
最新推荐文章于 2023-03-15 18:08:10 发布