题目链接:Merge Two Sorted Lists
仔细读题目并理解题意!!!!!!!
这道题是要Merge two sorted linked lists,重点是sorted,将已经排好序的列表合并,那么合并后的列表自然也是排好序的。
刚开始没注意到排序问题,一直不知道问题出现在哪里,后来发现是这么弱智的问题,简直有毒啊啊啊啊啊
思路:通过比较l1和l2值得大小,将小的值加入到l3,并且指向next;当一个列表指向null时,那么直接将另一个列表的剩余部分加入到l3
代码:
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l2==null)
return l1;
if(l1==null)
return l2;
ListNode head = new ListNode(-1);
ListNode l3 = head;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
l3.next = new ListNode(l1.val);
l3 = l3.next;
l1 = l1.next;
}
else {
l3.next = new ListNode(l2.val);
l3 = l3.next;
l2 = l2.next;
}
}
if(l1==null)
l3.next = l2;
else
l3.next = l1;
return head.next;
}
}
同样在网上看到了有人使用递归的方式实现。
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l2==null)
return l1;
if(l1==null)
return l2;
ListNode l3;
if(l1.val<l2.val){
l3 = l1;
l3.next = mergeTwoLists(l1.next,l2);
}
else {
l3 = l2;
l3.next = mergeTwoLists(l1,l2.next);
}
return l3;
}
}