兩個有序鏈表合併爲一個有序鏈表(Java實現)

解題思路:

以升序爲例

第一步當然是判空  如果其中一個鏈表爲空  則返回另一個鏈表即可

要有序 所以需要比較結點大小  創建兩個引用指向兩個鏈表  同時分別創建將要合成鏈表的頭和尾

比較兩個結點的大小  將較小的結點 cur 放到新的鏈表尾部 

此時要考慮特殊情況 當新鏈表爲空時  要把頭和尾都設置成 cur 同時 cur 向後移 

新鏈表不爲空時將 cur  放到尾部 同時 newTail 和 cur 向後移

最後再處理循環結束時 一個鏈表爲空 另一個不爲空的情況 直接將非空鏈表併到新鏈表尾部即可

//將兩個有序鏈表合併爲一個新的有序鏈表(升序爲例)
    public ListNode conflateList(ListNode head1,ListNode head2) {
        //先進行判空
        if (head1 == null) {
            return head2;
        }
        if (head2 == null) {
            return head1;
        }
        //設置兩個引用分別指向兩個鏈表
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        //設置將要合成的鏈表的頭和尾
        ListNode newHead = null;
        ListNode newTail = null;
        //兩個鏈表任何一個爲空循環就終止
        while (cur1 != null && cur2 != null) {
            if (cur1.val <= cur2.val) {
                if (newHead == null) {
                    //當新鏈表爲空時
                    newHead = cur1;
                    newTail = cur1;
                    cur1 = cur1.next;
                }
                //新鏈表不爲空時
                newTail.next = cur1;
                newTail = newTail.next;
                cur1 = cur1.next;
            } else {
                if (newHead == null) {
                    newHead = cur2;
                    newTail = cur2;
                    cur2 = cur2.next;
                }
                newTail.next = cur2;
                newTail = newTail.next;
                cur2 = cur2.next;
            }
        }
        //循環終止之後 把還剩有結點的鏈表併到新鏈表尾部即可
        if (cur1 == null) {
            newTail.next = cur2;
        } else {
            newTail.next = cur1;
        }
        return newHead;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章