合并两个有序链表
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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
迭代法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// 两条链表都为null 直接返回null
if(l1==null&&l2==null)
return null;
if(l1==null) // l1为null 直接返回l2
return l2;
if(l2==null) // l2 为null, 直接返回l1
return l1;
// cur 保存当前尾节点 temp 保存即将接上的节点 head 为头结点
ListNode cur=null,temp=null,head=null;
while(l1!=null&&l2!=null)
{
if(l1.val>=l2.val)
{
temp = l2;
l2 = l2.next;
}
else
{
temp = l1;
l1 = l1.next;
}
if(head==null)
cur = head = temp;
else
{
cur.next = temp;
cur = temp;
}
}
if(l1==null)
cur.next = l2;
else
cur.next = l1;
return head;
}
}
递归法:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
if(l1.val>=l2.val)
{
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}else
{
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
}
}