LeetCode 第 21 題 (Merge Two Sorted Lists)
LeetCode 第 21 題 (Merge Two Sorted Lists)
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.
合併兩個排好序的連結串列,要求合併之後的連結串列仍然是排好序的。題目的要求給的並不明確,沒有說合並之後的連結串列需要排好序的。但是出題人的意圖確實是這樣的。
這個題目比較簡單,技巧呢仍然是提前建立一個頭節點。這樣能簡化程式碼。
程式裡同時維護著三個指標, l1、l2、和 p。l1、l2 用來遍歷輸入的兩個連結串列。並依次將較小的元素插入到 p 這個連結串列中。具體的程式碼如下。
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode head(0), *p = &head;
while(l1 && l2)
{
if(l1->val <= l2->val)
{
p->next = l1;
l1 = l1->next;
}
else
{
p->next = l2;
l2 = l2->next;
}
p = p->next;
}
if(l1 == NULL) p->next = l2;
if(l2 == NULL) p->next = l1;
return head.next;
}
相關文章
- Leetcode 21 Merge Two Sorted ListsLeetCode
- LeetCode 21. Merge Two Sorted ListsLeetCode
- leetcode21_Merge Two Sorted ListsLeetCode
- Leetcode Merge Two Sorted ListsLeetCode
- Leetcode-Merge Two Sorted ListsLeetCode
- Merge Two Sorted Lists leetcode javaLeetCodeJava
- 資料結構與演算法 | Leetcode 21:Merge Two Sorted Lists資料結構演算法LeetCode
- LeetCode Merge Two Sorted Lists(021)解法總結LeetCode
- [LeetCode] Merge Two Sorted Lists 混合插入有序連結串列LeetCode
- Leetcode Merge k Sorted ListsLeetCode
- Leetcode 23 Merge k Sorted ListsLeetCode
- Leetcode-Merge k Sorted ListsLeetCode
- Merge k Sorted Lists leetcode javaLeetCodeJava
- 【Leetcode】23. Merge k Sorted ListsLeetCode
- leetcode23_Merge k Sorted ListsLeetCode
- [LintCode] Merge Two Sorted Lists 混合插入有序連結串列
- LeetCode 之 JavaScript 解答第23題 —— 合併K個有序連結串列(Merge K Sorted Lists)LeetCodeJavaScript
- [LeetCode] Merge k Sorted Lists 合併k個有序連結串列LeetCode
- Leetcode Merge Sorted ArrayLeetCode
- [leetCode][003] Intersection of Two Linked ListsLeetCode
- Leetcode-Intersection of Two Linked ListsLeetCode
- Fourth. LeetCode 21:MergeTwo Sorted Lists 合併兩個有序連結串列LeetCode
- Leetcode Median of Two Sorted ArraysLeetCode
- Leetcode-Merge Sorted ArrayLeetCode
- Leetcode 4 Median of Two Sorted ArraysLeetCode
- Leetcode-Median of Two Sorted ArraysLeetCode
- Median of Two Sorted Array leetcode javaLeetCodeJava
- Leetcode 88. Merge Sorted ArrayLeetCode
- Leetcode 160. Intersection of Two Linked ListsLeetCode
- 【Leetcode】160. Intersection of Two Linked ListsLeetCode
- LeetCode 4. Median of Two Sorted ArraysLeetCode
- LeetCode2:Median of Two Sorted ArraysLeetCode
- LeetCode 第 231 題 (Power of Two)LeetCode
- 【LeetCode 88_陣列】Merge Sorted ArrayLeetCode陣列
- 【LeetCode】617. Merge Two Binary TreesLeetCode
- LeetCode 617. Merge Two Binary TreesLeetCode
- LeetCode Median of Two Sorted Arrays(004)解法總結LeetCode
- 【Leetcode】167. Two Sum II - Input array is sortedLeetCode