一.题目

Merge Two Sorted Lists

Total Accepted: 63974 Total Submissions: 196044My
Submissions

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.

Show Tags
Have you met this question in a real interview?

Yes
No

Discuss










二.解题技巧

    这道题就是将两个已排序的列表的元素进行比較,当某一个列表的元素比較小的话。就将其增加到输出列表中。并将该列表的指针指向列表的下一个元素。这道题是比較简单的,可是有一个边界条件要注意,就是两个列表可能会出现为空的情况,假设l1为空时,能够直接将l2进行返回;假设l2为空时,能够直接将l1返回,这样能够降低非常多计算量。



三.实现代码

#include <iostream>

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/ struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
}; class Solution
{
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
if (!l1)
{
return l2;
} if (!l2)
{
return l1;
} ListNode Head(0);
ListNode *Pre = &Head; while(l1 && l2)
{
if (l1->val < l2->val)
{
Pre->next = l1;
l1 = l1->next;
Pre = Pre->next;
}
else
{
Pre->next = l2;
l2 = l2->next;
Pre = Pre->next;
}
} while (l1)
{
Pre->next = l1;
l1 = l1->next;
Pre = Pre->next;
} while(l2)
{
Pre->next = l2;
l2 = l2->next;
Pre = Pre->next;
} return Head.next; }
};



四.体会

   这道题主要考察的就是边界条件,主要就是处理链表为空的情况,也就是,假设l1为空。就返回l2,假设l2为空,就直接返回l1。

简单的题要考虑充分啊。




版权全部,欢迎转载。转载请注明出处,谢谢




最新文章

  1. Struts2中Date日期转换的问题
  2. [2016湖南长沙培训Day4][前鬼后鬼的守护 chen] (动态开点线段树+中位数 or 动规 or 贪心+堆优化)
  3. SQLite XXTea加密学习
  4. NetworkComms框架介绍 完美支持TCP/UDP协议
  5. NPM使用
  6. sqlserver复杂排序(order by case when)
  7. oracle表设置主键自增长
  8. MVC模式已死
  9. nginx浏览目录
  10. 8.21.2 深入finally语句快
  11. 闪付卡(QuickPass)隐私泄露原理
  12. mvn clean compile package install deploy
  13. js弹出层
  14. 049 DSL语句
  15. 《Linux内核分析》第八周学习总结
  16. 部署一个不依赖tomcat容器的应用
  17. The hyperlink for cell A2 references relation rId1, but that didn&#39;t exist!
  18. Linux下升级openssl
  19. js动态移动滚动条至底部示例
  20. python decimal和fractions模块

热门文章

  1. SQL中on条件与where条件的区别(转载)
  2. HTML - HTML Commonly Used Character Entities
  3. [置顶] Android下实现自动关机的方法总结
  4. android源码地址及下载介绍
  5. javaee加密部署,tomcat使用自己的classloader解密【正解】
  6. BMP文件结构
  7. http协议与web本质
  8. Head First PHP &amp;amp;MySQL学习笔记
  9. 进阶-案例九: WD中实现export 到Excel,Doc,Txt.
  10. _00024 尼娜抹微笑伊拉克_云计算ClouderaManager以及CHD5.1.0群集部署安装文档V1.0