国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LintCode/LeetCode] Merge Two Sorted Lists

dockerclub / 1411人閱讀

摘要:先考慮和有無空集,有則返回另一個。新建鏈表,指針將和較小的放在鏈表頂端,然后向后遍歷,直到或之一為空。再將非空的鏈表放在后面。

Problem

Merge two sorted (ascending) linked lists and return it as a new sorted list. The new sorted list should be made by splicing together the nodes of the two lists and sorted in ascending order.

Example

Given 1->3->8->11->15->null, 2->null, return 1->2->3->8->11->15->null.

Note

先考慮l1和l2有無空集,有則返回另一個。
新建鏈表dummy,指針node將l1和l2較小的放在鏈表頂端,然后向后遍歷,直到l1或l2之一為空。再將非空的鏈表放在node后面。最后返回dummy.next結束。

Solution
public class Solution {
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        ListNode dummy = new ListNode(0), node = dummy;
        while (l1 != null && l2 != null) {
            if (l1.val < l2.val) {
                node.next = l1;
                l1 = l1.next;
            }
            else {
                node.next = l2;
                l2 = l2.next;
            }
            node = node.next;
        }
        if (l1 != null) node.next = l1;
        if (l2 != null) node.next = l2;
        return dummy.next;
    }
}

文章版權歸作者所有,未經允許請勿轉載,若此文章存在違規行為,您可以聯系管理員刪除。

轉載請注明本文地址:http://specialneedsforspecialkids.com/yun/65703.html

相關文章

  • [LintCode/LeetCode] Merge Sorted Array

    Problem Given two sorted integer arrays A and B, merge B into A as one sorted array. Notice You may assume that A has enough space (size that is greater or equal to m + n) to hold additional elements ...

    summerpxy 評論0 收藏0
  • [Leetcode] Merge Two Sorted Lists Merge K Sorted L

    摘要:注意因為堆中是鏈表節點,我們在初始化堆時還要新建一個的類。代碼初始化大小為的堆拿出堆頂元素將堆頂元素的下一個加入堆中 Merge Two Sorted Lists 最新更新請見:https://yanjia.me/zh/2019/01/... Merge two sorted linked lists and return it as a new list. The new list...

    stefanieliang 評論0 收藏0
  • LeetCode Easy】021 Merge Two Sorted Lists

    摘要:為減小空間復雜度,最后結果直接修改在上,不重新給分配空間。 Easy 021 Merge Two Sorted Lists Description: Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes o...

    icattlecoder 評論0 收藏0
  • leetcode21 Merge Two Sorted Lists 將兩個有序鏈表組合成一個新的有

    摘要:題目要求翻譯過來就是將兩個有序的鏈表組合成一個新的有序的鏈表思路一循環在當前兩個鏈表的節點都是非空的情況下比較大小,較小的添入結果鏈表中并且獲得較小節點的下一個節點。 題目要求 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing togeth...

    BothEyes1993 評論0 收藏0
  • Leetcode 21 Merge Two Sorted Lists

    摘要:題目詳情題目要求我們將兩個有序鏈表合成一個有序的鏈表。輸入輸出想法首先要判斷其中一個鏈表為空的狀態,這種情況直接返回另一個鏈表即可。每次遞歸都會獲得當前兩個鏈表指針位置的值較小的節點,從而組成一個新的鏈表。 題目詳情 Merge two sorted linked lists and return it as a new list. The new list should be mad...

    xbynet 評論0 收藏0

發表評論

0條評論

最新活動
閱讀需要支付1元查看
<