摘要:先考慮和有無空集,有則返回另一個。新建鏈表,指針將和較小的放在鏈表頂端,然后向后遍歷,直到或之一為空。再將非空的鏈表放在后面。
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.
ExampleGiven 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結束。
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
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 ...
摘要:注意因為堆中是鏈表節點,我們在初始化堆時還要新建一個的類。代碼初始化大小為的堆拿出堆頂元素將堆頂元素的下一個加入堆中 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...
摘要:為減小空間復雜度,最后結果直接修改在上,不重新給分配空間。 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...
摘要:題目要求翻譯過來就是將兩個有序的鏈表組合成一個新的有序的鏈表思路一循環在當前兩個鏈表的節點都是非空的情況下比較大小,較小的添入結果鏈表中并且獲得較小節點的下一個節點。 題目要求 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing togeth...
摘要:題目詳情題目要求我們將兩個有序鏈表合成一個有序的鏈表。輸入輸出想法首先要判斷其中一個鏈表為空的狀態,這種情況直接返回另一個鏈表即可。每次遞歸都會獲得當前兩個鏈表指針位置的值較小的節點,從而組成一個新的鏈表。 題目詳情 Merge two sorted linked lists and return it as a new list. The new list should be mad...
閱讀 1163·2021-11-15 18:14
閱讀 3627·2021-11-15 11:37
閱讀 754·2021-09-24 09:47
閱讀 2427·2021-09-04 16:48
閱讀 2182·2019-08-30 15:53
閱讀 2379·2019-08-30 15:53
閱讀 390·2019-08-30 11:20
閱讀 1232·2019-08-29 16:08