归并排序 单链表

来源:互联网 发布:苹果手机 解压软件 编辑:程序博客网 时间:2024/06/05 16:55

package com.weibo.linkedlist;


public class GuibingSortList {

staticclass Node {

    public Nodenext;

    publicint val;

}

public static Node merge(Node a, Node b) {

    Node dummyHead,curr;

    dummyHead =new Node();

    curr =dummyHead;

    while (a !=null && b !=null) {

        if (a.val <=b.val) {

            curr.next =a;

            a =a.next;

        } else {

            curr.next =b;

            b =b.next;

        }

        curr =curr.next;

    }

    curr.next = (a ==null) ? b :a;

    returndummyHead.next;

}


public static  Node getMiddle(Node head) {

    if (head ==null) {

        returnhead;

    }

    Node slow,fast

    slow =fast = head;

    while (fast.next !=null && fast.next.next !=null) {

        slow =slow.next;

        fast =fast.next.next;

    }

    returnslow;

}

public static  Node merge_sort(Node head) {

    if (head ==null || head.next ==null) {

        returnhead;

    }

    Node middle = getMiddle(head); 

    Node sHalf =middle.next;

    middle.next =null;


    return merge(merge_sort(head), merge_sort(sHalf)); 

}

}


原创粉丝点击