原题链接:https://oj.leetcode.com/problems/merge-two-sorted-lists/
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.
我的思路:可以再create一个新的链表,作为返回结果吗?可以。如果不行,该怎么做?
Time: O(min(m, n)), Space: O(1)
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode prev = new ListNode(0);//the result list
prev.next = null;
ListNode temp = prev;
while(l1!=null && l2!=null){
if(l1.val < l2.val){
prev.next = l1;
l1 = l1.next;
}
else{
prev.next = l2;
l2 = l2.next;
}
prev = prev.next;
}
if(l1!=null) prev.next = l1;//当两链表之一还有剩余时,只需把当前prev.next指向头节点,不用再逐个遍历剩下节点。因此时间复杂度是O(min(m,n))
else prev.next = l2;
return temp.next;
}
}
@8.30.2014 已做第二遍。不用再做。