/**
*
* 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.
*
*/
public class MergeTwoSortedLists {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
// 208 / 208 test cases passed.
// Status: Accepted
// Runtime: 282 ms
// Submitted: 0 minutes ago
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = new ListNode(-1);
ListNode cursor = head;
while(l1 != null && l2 != null) {
if(l1.val <= l2.val) {
cursor.next = l1;
l1 = l1.next;
} else {
cursor.next = l2;
l2 =l2.next;
}
cursor = cursor.next;
}
cursor.next = (l1 == null) ? l2 : l1;
return head.next;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}