单链表归并排序

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();
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值