题目描述:
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.
合并两个排序链表并返回一个新的列表。新的链表的结果由原先的两个链表结点组成,也就是不能合并后的链表不能包含新创建的结点。
代码:
/**
* 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) {
ListNode rt = new ListNode(0);
ListNode h = rt;
while( l1 != null && l2 != null){
if(l1.val < l2.val){
rt.next = l1;
l1 = l1.next;
}else{
rt.next = l2;
l2 = l2.next;
}
rt = rt.next;
}
if(l1 != null) rt.next = l1;
else rt.next = l2;
return h.next;
}
}