LeetCode -- Merge Two Sorted Linked List
2015-08-29 21:36
316 查看
Question:
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.
Analysis:
1)两个都是空串;
2)一个是空串;
3)新建一个伪头结点,用于新串的连接;
4)最后还要检查是否有一个串还有数字。
Answer:
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.
Analysis:
1)两个都是空串;
2)一个是空串;
3)新建一个伪头结点,用于新串的连接;
4)最后还要检查是否有一个串还有数字。
Answer:
public ListNode mergeTwoLists(ListNode l1, ListNode l2) { ListNode p1 = l1; ListNode p2 = l2; if(l1 == null && l2 == null) return null; if(l1 == null && l2 != null) return l2; if(l1 != null && l2 == null) return l1; ListNode fakeHead = new ListNode(0); ListNode p = fakeHead; while (p1 != null && p2 != null){ if (p1.val <= p2.val) { p.next = p1; p1 = p1.next; p = p.next; } else { p.next = p2; p2 = p2.next; p = p.next; } } if(p1 != null) p.next = p1; if(p2 != null) p.next = p2; return fakeHead.next; }
相关文章推荐
- 1、CC2541蓝牙4.0芯片中级教程——基于OSAL操作系统的运行流程了解+定时器和串口例程了解
- MVC学习笔记---MVC生命周期
- Python文件读写
- 网络流习题
- inotify-tools、sersync配置及压力测试
- Altium Designer官方库下载地址(自己知道芯片公司的话这里很方便)
- 项目1------智慧北京
- 数组参数传递时需要注意的事项
- SQL基本语法(笔记)
- Linux sort 命令
- 腾讯在线模拟笔试-2016涉及知识点
- LeetCode Ugly Number
- muduo网络库源码学习————线程特定数据
- 了解 JavaScript (3)- 马上开始
- Android Studio plugins recommend
- php大力力 [036节] 后台系统的登录页面界面做完啦
- Hadoop中两表JOIN的处理方法(转)
- 初来咋到~~~
- 懒加载的坑
- 内网渗透浅析