【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 of the first two lists.
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

My Solution:

  1. 爲減少空間複雜度,最後結果直接修改在list1上,不從新給result分配空間。具體作法,兩個指針分別同時遍歷兩個list,每次指針指向的值進行比較,較小的加入list1,而且相應指針後移要注意邊界狀況,list1/2中任何一個爲null就返回另外一個;當list1到結尾了而list2還未遍歷完,則把list2剩下的直接加到list1的末尾(由於已經sorted了)
相關文章
相關標籤/搜索