Merge Two Sorted Lists
2015-11-19 12:50
274 查看
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.
用了一个dumb head,。对于这种header不确定的list,可以用dumb header,代码会整洁不少。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dumHeader = new ListNode(0);
ListNode current = dumHeader;
while(l1 != null && l2 != null){
ListNode nextNode = null;
if(l1.val > l2.val){
nextNode = l2;
l2 = l2.next;
current.next = nextNode;
current = nextNode;
}
else if(l2.val >= l1.val){
nextNode = l1;
l1 = l1.next;
current.next = nextNode;
current = nextNode;
}
}
if(l1 != null){
current.next = l1;
}
else if (l2 != null){
current.next = l2;
}
return dumHeader.next;
}
}
two lists.
用了一个dumb head,。对于这种header不确定的list,可以用dumb header,代码会整洁不少。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dumHeader = new ListNode(0);
ListNode current = dumHeader;
while(l1 != null && l2 != null){
ListNode nextNode = null;
if(l1.val > l2.val){
nextNode = l2;
l2 = l2.next;
current.next = nextNode;
current = nextNode;
}
else if(l2.val >= l1.val){
nextNode = l1;
l1 = l1.next;
current.next = nextNode;
current = nextNode;
}
}
if(l1 != null){
current.next = l1;
}
else if (l2 != null){
current.next = l2;
}
return dumHeader.next;
}
}
相关文章推荐
- 用maven将swing项目打成可执行jar包(含依赖)
- 获取当前时间,当前时间加减计算
- Java 学习笔记14:Spring 数据库数据源DBCP配置说明
- c中宏定义的一些应用积累
- Bucket不为空,请检查该Bucket是否包含未删除的Object或者未成功的Multipart碎片
- hdu A Magic Lamp
- == 与 .equals 的区别
- 顺序表(C实现)
- java获取文 件的MD5值
- POJ 3522 Slim Span 最小差值生成树
- ID3算法(决策树)
- 关于C++中的cin的一点理解
- javascript------JSON
- 工具收集篇
- Servlet:response和request
- you must restart adb and eclipse的相关解决办法
- Android——显示隐藏移动动画
- 基于模板匹配和遗传算法的人眼定位
- POI操作官网API
- [转]如何处理UI对象和场景对象点击事件冲突/重复