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.
分析:我在做的是设置了一个临时头结点head,和一个当前已排好序的链表的最后一个节点p,时刻保持head.next 到 p是有序的。
/**
* 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) {
if(l1==null && l2==null){
return null;
}
ListNode head = new ListNode(0);//先暂时保存一个临时的头结点
ListNode p = head;
while(l1!=null && l2!=null){
if(l1.val <= l2.val){
p.next = l1;
l1=l1.next;
p = p.next;
}else{
p.next = l2;
l2=l2.next;
p = p.next;
}
}
if(l1 == null){
p.next = l2;
}else{
p.next = l1;
p = p.next;
}
return head.next;
}
}
/**
* 递归做。
*/
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null){
return l2;
}
if(l2 == null){
return l1;
}
if(l1.val <= l2.val){
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
}