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.
Example:
Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4
Problem Clarification
We cannot copy the nodes.Idea – 1
Merge routine in mergesort, time
/**
* 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 dummy = new ListNode(-1);
ListNode t = dummy;
while(l1 != null && l2 != null)
{
if(l1.val < l2.val)
{
t.next = l1;
l1 = l1.next;
}
else
{
t.next = l2;
l2 = l2.next;
}
t = t.next;
}
if(l1 != null)
{
t.next = l1;
}
else
{
t.next = l2;
}
return dummy.next;
}
}
Runtime: 1 ms, faster than 88.84% of Java online submissions for Merge Two Sorted Lists.
Memory Usage: 37.1 MB, less than 97.90% of Java online submissions for Merge Two Sorted Lists.