摘要:先考慮和有無空集,有則返回另一個(gè)。新建鏈表,指針將和較小的放在鏈表頂端,然后向后遍歷,直到或之一為空。再將非空的鏈表放在后面。
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有無空集,有則返回另一個(gè)。
新建鏈表dummy,指針node將l1和l2較小的放在鏈表頂端,然后向后遍歷,直到l1或l2之一為空。再將非空的鏈表放在node后面。最后返回dummy.next結(jié)束。
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; } }
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://systransis.cn/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 ...
摘要:注意因?yàn)槎阎惺擎湵砉?jié)點(diǎn),我們在初始化堆時(shí)還要新建一個(gè)的類。代碼初始化大小為的堆拿出堆頂元素將堆頂元素的下一個(gè)加入堆中 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...
摘要:為減小空間復(fù)雜度,最后結(jié)果直接修改在上,不重新給分配空間。 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...
摘要:題目要求翻譯過來就是將兩個(gè)有序的鏈表組合成一個(gè)新的有序的鏈表思路一循環(huán)在當(dāng)前兩個(gè)鏈表的節(jié)點(diǎn)都是非空的情況下比較大小,較小的添入結(jié)果鏈表中并且獲得較小節(jié)點(diǎn)的下一個(gè)節(jié)點(diǎn)。 題目要求 Merge two sorted linked lists and return it as a new list. The new list should be made by splicing togeth...
摘要:題目詳情題目要求我們將兩個(gè)有序鏈表合成一個(gè)有序的鏈表。輸入輸出想法首先要判斷其中一個(gè)鏈表為空的狀態(tài),這種情況直接返回另一個(gè)鏈表即可。每次遞歸都會(huì)獲得當(dāng)前兩個(gè)鏈表指針位置的值較小的節(jié)點(diǎn),從而組成一個(gè)新的鏈表。 題目詳情 Merge two sorted linked lists and return it as a new list. The new list should be mad...
閱讀 1173·2021-11-15 18:14
閱讀 3646·2021-11-15 11:37
閱讀 768·2021-09-24 09:47
閱讀 2455·2021-09-04 16:48
閱讀 2189·2019-08-30 15:53
閱讀 2390·2019-08-30 15:53
閱讀 400·2019-08-30 11:20
閱讀 1244·2019-08-29 16:08