【LeetCode Easy】021 Merge Two Sorted Lists

0

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了)

你可能感兴趣的

载入中...