1. 程式人生 > >【LeetCode】21. Merge Two Sorted Lists - Java實現

【LeetCode】21. Merge Two Sorted Lists - Java實現

文章目錄

1. 題目描述:

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

2. 思路分析:

題目的意思是合併2個有序的連結串列。

思路是用2個指標分別指向2個連結串列,比較2個節點,將較小的節點放入結果連結串列中並且指標後移。

3. Java程式碼:

原始碼見我GiHub主頁

程式碼:

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
    if (l1 == null) {
        return l2;
    }
    if (l2 == null) {
        return l1;
    }

    ListNode result =
new ListNode(0); ListNode cur = result; while (l1 != null && l2 != null) { if (l1.val < l2.val) { cur.next = l1; l1 = l1.next; } else { cur.next = l2; l2 = l2.next; } cur = cur.next; } if (l1 !=
null) { cur.next = l1; } if (l2 != null) { cur.next = l2; } return result.next; }