题目描述:
将两个有序链表合并为一个新的有序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入: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 tmp1 = l1;
ListNode tmp2 = l2;
ListNode res = new ListNode(0);
ListNode res1 = res;
while(tmp1!=null && tmp2!=null){
if(tmp1.val<=tmp2.val){
res.next = new ListNode(tmp1.val);
res = res.next;
tmp1 = tmp1.next;
}else{
res.next = new ListNode(tmp2.val);
res=res.next;
tmp2 = tmp2.next;
}
}
if(tmp1==null){
res.next = tmp2;
}
if(tmp2==null){
res.next = tmp1;
}
return res1.next;
}
}
网友评论