LeetCode—21. Merge Two Sorted Lists
题目
两个有序链表,合并成一个。题目里有一句话我没理解好,她说“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; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null && l2 == null) {
return null;
}
if(l1 == null) return l2;
if(l2 == null) return l1;
ListNode res = new ListNode(0);
ListNode pre = res;
while(l1!=null && l2!=null){
if(l1.val<=l2.val){
pre.next = l1;
l1 = l1.next;
}else{
pre.next = l2;
l2 = l2.next;
}
pre = pre.next;
}
if(l1!=null){
pre.next = l1;
}
if(l2!=null){
pre.next = l2;
}
return res.next;
}
}