将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出: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) {
ListNode cur = new ListNode(0);
ListNode node = cur;
while(l1!=null && l2 != null){
//l1 和 l2 谁的值小,将其存入node中,然后将谁的链表后移一位。
if(l1.val <= l2.val){
node.next = l1;
node = node.next;
l1 = l1.next;
}else{
node.next = l2;
node = node.next;
l2 = l2.next;
}
}
// 谁的先为空,将另一个的剩余元素 ,全部加在node后面。
if (l1 == null) {
node.next = l2;
} else {
node.next = l1;
}
return cur.next;
}
}