LeetCode_合併兩個有序鏈表_LinkedList_E

21. 合併兩個有序鏈表

pre:

/**
 * 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 res = null, curr = null;
        while (l1 != null || l2 != null) {
            ListNode node;
            if (l1 != null && l2 != null) {
                if (l1.val < l2.val) {
                    node = new ListNode(l1.val);
                    l1 = l1.next;
                } else {
                    node = new ListNode(l2.val);
                    l2 = l2.next;
                }
            } else if (l1 != null) {
                node = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                node = new ListNode(l2.val);
                l2 = l2.next; 
            }

            if (res == null) {
                res = node;
            } else {
                curr.next = node;
            }
            curr = node;
        }
        return res;
    }
}

別人的,邏輯一樣,稍微優化一下寫法:

/**
 * 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 head = new ListNode(0);
        ListNode curr = head;
        while (l1 != null && l2 != null) {
            ListNode node;
            if (l1.val < l2.val) {
                node = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                node = new ListNode(l2.val);
                l2 = l2.next;
            }
            curr.next = node;
            curr = node;
        }
        // 如果有剩下不爲null的,則直接掛在尾巴
        if (l1 != null) {
            curr.next = l1;
        } 
        if (l2 != null) {
            curr.next = l2;
        }
        return head.next;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章