LeetCode-21合併兩個有序列表

描述

將兩個升序鏈表合併爲一個新的升序鏈表並返回。新鏈表是通過拼接給定的兩個鏈表的所有節點組成的。

示例

輸入:1->2->4, 1->3->4
輸出:1->1->2->3->4->4

解法

  1. 初始解法:
    這個問題轉換爲經典的merge排序中的merge過程. merge排序中merge操作即是將兩個有序子數組合併成一個數組,需要考慮比較過程中左邊右邊索引到達邊界的情況. 而此題是將原始的數組存儲的子序列merge過程變爲以鏈表存儲的兩個子有序鏈表的merge過程,因此想到的第一個解法爲:
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode left = l1;
        ListNode right = l2;
        ListNode header = null;
        ListNode tail = header;
        ListNode node = null;
        while(left != null && right != null) {
            if(left.val > right.val) {
                if(header == null) {
                    header = new ListNode(right.val);
                    tail = header;
                } else {
                    node = new ListNode(right.val);
                    tail.next = node;
                    tail = tail.next;
                }
                right = right.next;
            } else {
                if(header == null) {
                    header = new ListNode(left.val);
                    tail = header;
                } else {
                    node = new ListNode(left.val);
                    tail.next = node;
                    tail = tail.next;
                }
                left = left.next;
            }
        }
        //邊界處理 左邊子鏈表遍歷完畢
        if(left == null) {
            if(tail == null) {
                if(right != null) {
                    tail = right;
                    header = tail;
                }
            } else {
                tail.next = right;
            }
        }
        // 右邊子鏈表遍歷完畢
        if(right == null) {
            if(tail == null) {
                if(left != null) {
                    tail = left;
                    header = tail;
                }
            } else {
                tail.next = left;
            }
        }
        return header;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章