【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了)
相关文章
相关标签/搜索