劍指Offer-合併兩個排序的鏈表

題目描述

輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,固然咱們須要合成後的鏈表知足單調不減規則。java

思路

思路一(迭代):this

  1. 首先處理空鏈表,當其中一個爲空鏈表時,直接輸出另外一個;當兩個均爲空鏈表時,輸出null。
  2. 初始化兩個鏈表頭,其中一個表頭用以記錄兩個鏈表比較後的結果,另外一個用來返回結果。
  3. 循環,若是兩個鏈表不爲空,進行比較,並將值小的賦給合併的鏈表頭cur,值小的鏈表向後移動一位,合併鏈表cur向後移動一位。
  4. 若是兩個鏈表有一爲空,循環結束,把未結束的鏈表直接鏈接到合併鏈表的尾部。

思路二(遞歸):spa

  1. 首先處理空鏈表,當其中一個爲空鏈表時,直接輸出另外一個;當兩個均爲空鏈表時,輸出null。
  2. 比較 list1 和 list2 的頭結點,較小的頭結點做爲合併後新鏈表的頭結點
  3. 肯定新鏈表的頭結點以後,就能夠遞歸比較餘下的結點了

代碼實現

package LinkedList;

/**
 * 合併兩個排序的鏈表
 * 輸入兩個單調遞增的鏈表,輸出兩個鏈表合成後的鏈表,固然咱們須要合成後的鏈表知足單調不減規則。
 */
public class Solution39 {
    /**
     * 迭代
     *
     * @param list1
     * @param list2
     * @return
     */
    public ListNode Merge_2(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null)
            return null;
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;
        //新建一個頭結點,用來存放合併的鏈表
        ListNode head = new ListNode(-1);
        ListNode cur = head;
        while (list1 != null && list2 != null) {
            if (list1.val < list2.val) {//若是鏈表1的結點小於鏈表2的結點
                cur.next = list1;
                list1 = list1.next;
            } else {
                cur.next = list2;
                list2 = list2.next;
            }
            cur = cur.next;
        }
        //把未結束的鏈表直接鏈接到合併鏈表的尾部
        if (list1 != null) cur.next = list1;
        if (list2 != null) cur.next = list2;
        return head.next;
    }

    /**
     * 遞歸
     *
     * @param list1
     * @param list2
     * @return
     */
    public ListNode Merge(ListNode list1, ListNode list2) {
        if (list1 == null && list2 == null)
            return null;
        if (list1 == null)
            return list2;
        if (list2 == null)
            return list1;
        if (list1.val <= list2.val) {//若是鏈表1的結點小於等於鏈表2的結點
            list1.next = Merge(list1.next, list2);
            return list1;
        } else {
            list2.next = Merge(list1, list2.next);
            return list2;
        }
    }

    public class ListNode {
        int val;
        ListNode next = null;

        ListNode(int val) {
            this.val = val;
        }
    }
}
相關文章
相關標籤/搜索