亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

合并排序鏈接列表

合并排序鏈接列表

郎朗坤 2019-10-15 15:20:25
我最近重新整理了一些基本知識,發現合并對鏈表進行排序是一個非常好的挑戰。如果您有一個好的實現,那么請在此處展示它。
查看完整描述

3 回答

?
斯蒂芬大帝

TA貢獻1827條經驗 獲得超8個贊

想知道為什么它應該是這里所說的巨大挑戰,這是Java中沒有任何“聰明把戲”的簡單實現。


//The main function

public static Node merge_sort(Node head) 

{

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

        return head;


    Node middle = getMiddle(head);      //get the middle of the list

    Node left_head = head;

    Node right_head = middle.next; 

    middle.next = null;             //split the list into two halfs


    return merge(merge_sort(left_head), merge_sort(right_head));  //recurse on that

}


//Merge subroutine to merge two sorted lists

public static Node merge(Node a, Node b)

{

    Node dummyHead = new Node();


    for(Node current  = dummyHead; a != null && b != null; current = current.next;)

    {

        if(a.data <= b.data) 

        {

            current.next = a; 

            a = a.next; 

        }

        else

        { 

            current.next = b;

            b = b.next; 

        }


    }

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

    return dummyHead.next;

}


//Finding the middle element of the list for splitting

public static Node getMiddle(Node head)

{

    if(head == null) 

        return head;


    Node slow = head, fast = head;


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

    {

        slow = slow.next;

        fast = fast.next.next;

    }

    return slow;

}


查看完整回答
反對 回復 2019-10-15
  • 3 回答
  • 0 關注
  • 655 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號