合并链表题解
合并有序链表
http://www.nowcoder.com/questionTerminal/a479a3f0c4554867b35356e0d57cf03d
public class Solution {
public ListNode mergeTwoLists (ListNode l1, ListNode l2) {
// write code here
//思路:l1,l2有序,合并后的链表也要有序
if(l1==null) return l2;
if(l2==null) return l1;
ListNode node = new ListNode(-1);
ListNode res = node;//res保存为头结点
while(l1!=null || l2!=null){
int x = l1==null?Integer.MAX_VALUE:l1.val;
int y = l2==null?Integer.MAX_VALUE:l2.val;
if(x<y){
node.next = l1;
l1=l1.next;
}
else{
node.next = l2;
l2 = l2.next;
}
node = node.next;
}
return res.next;
}
}