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.
Subscribe to see which companies asked this question
package leetcode;
public class Ways {
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode q = new ListNode(0);
ListNode p = q;
while (l1 != null || l2 != null) {
if (l1 != null && l2 != null) {
if (l1.val <l2.val) {
p.next = l1;
l1 = l1.next;
} else {
p.next = l2;
l2 = l2.next;
}
p = p.next;
} else if (l1 == null) {
p.next = l2;
break;
} else if (l2 == null) {
p.next = l1;
break;
}
}
return q.next;
}
public static void main(String[] args) {
ListNode a = new ListNode(1);
ListNode a1 = new ListNode(2);
ListNode a2 = new ListNode(3);
a.next = a1;
a1.next = a2;
//
ListNode b = new ListNode(1);
ListNode b1 = new ListNode(2);
b.next=b1;
ListNode c=mergeTwoLists(a,b);
while (c!=null) {
System.out.print(" " +c.val);
c=c.next;
}
}
}