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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
给定有序的两个数组,合并两个数组,并保持有序。
这其实是归并排序的其中一个步骤。
1 | /** |
tip:
- 两个参数是否空指针需要判断
result
提交过程错了两次,一次是因为空指针,一次是因为判断大小的语句里,还多余判断了一次下一个元素是不是空指针,导致少了个元素。
Runtime: 20 ms, faster than 9.56% of C++ online submissions for Merge Two Sorted Lists.
Memory Usage: 9.9 MB, less than 88.65% of C++ online submissions for Merge Two Sorted Lists.
内存占用太大,还有改进空间。
有个疑惑,其中一段代码改成以下这样后,内存占用竟然升高到10.1M
1 | if (l1->val <= l2->val) { |