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.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode dump = new ListNode(-1);
ListNode cursor = dump;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cursor.next=l1;
l1=l1.next;
cursor=cursor.next;
}else{
cursor.next=l2;
l2=l2.next;
cursor=cursor.next;
}
}
if(l1==null)
cursor.next=l2;
else
cursor.next=l1;
return dump.next;
}
}
/**
* 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)
return l2;
else if (l2 == null)
return l1;
if (l1.val > l2.val) {
l2.next = mergeTwoLists(l1,l2.next);
return l2;
}
l1.next = mergeTwoLists(l1.next,l2);
return l1;
}
}
JS
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
var mergeTwoLists = function(l1, l2) {
let l3 = new ListNode(-1),
p = l3;
while(l1 && l2) {
if (l1.val <= l2.val) {
p.next = new ListNode(l1.val);
l1 = l1.next;
} else {
p.next = new ListNode(l2.val);
l2 = l2.next;
}
p = p.next;
}
p.next = l1 ? l1 : l2;
return l3.next;
};
/**
* 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) return l2;
if (l2 == null) return l1;
ListNode result = new ListNode(0);
ListNode curr = result;
// add smallest from both lists
while (l1 != null) {
// if l2 is exhausted or l1 is smaller: add l1
if (l2 == null || l1.val <= l2.val) {
curr.next = l1;
curr = curr.next;
l1 = l1.next;
} else { // add l2
curr.next = l2;
curr = curr.next;
l2 = l2.next;
}
}
// finish rest of l2 if not exhausted
while (l2 != null) {
curr.next = l2;
curr = curr.next;
l2 = l2.next;
}
return result.next;
}
}
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode ans= new ListNode(0);
ListNode ansTemp = ans;
ListNode temp1 = l1;
ListNode temp2 = l2;
while(temp1!=null || temp2!=null){
if(temp2 == null || temp1 != null && temp1.val<=temp2.val){
ansTemp.next = temp1;
temp1 = temp1.next;
}
else if(temp1==null || temp2!=null && temp2.val < temp1.val){
ansTemp.next = temp2;
temp2 = temp2.next;
}
ansTemp = ansTemp.next;
}
return ans.next;
}
}