數據結構和算法之單向鏈表三:合並兩個有序鏈表


  我們以前在介紹排序算法的時候介紹過一種排序算法叫做歸並排序,我們現在需要思考一個問題,能不能利用歸並的思想對兩個有序的單向鏈表進行合並。

/**
     * 對兩個有序鏈表進行有序合並
     * 
     * @param head1
     * @param head2
     * @return
     */
    public Node mergeList(Node head1, Node head2) {
        // 判斷鏈表是否有為空的情況
        if (head1 == null && head2 == null) {
            return null;
        }
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        // 定義兩個節點
        Node first = null;
        Node current = null;
        // 選取頭結點
        if (head1.date > head2.date) {
            first = head2;
            current = first;
            head2 = head2.next;
        } else {
            first = head1;
            current = head1;
            head1 = head1.next;
        }
        // 對兩個鏈表進行合並
        while (head1 != null && head2 != null) {
            if (head1.date < head2.date) {
                current.next = head1;
                current = current.next;
                head1 = head1.next;
            } else {
                current.next = head2;
                current = current.next;
                head2 = head2.next;
            }
        }
        // 對剩下的節點進行合並
        while (head1 != null) {
            current.next = head1;
            head1 = head1.next;
            current = current.next;
        }
        while (head2 != null) {
            current.next = head2;
            head2 = head2.next;
            current = current.next;
        }
        return first;
    }

  請把這個方法放在單向鏈表的第一篇基礎方法里面進行測試即可,我們通過代碼可以很清楚的觀察到通篇利用的就是歸並的思想,對於兩個有序鏈表的整合。但是我們在這里需要提出注意的是,對於空指針這一項的控制,也就是對於鏈表為空的控制,這時鏈表進行操作時比較忌諱的問題。一定要提前對鏈表是否為空,或者對應節點是否為空進行應該有的判斷。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM