/* package whatever; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
class ListNode {
public int val;
public ListNode next;
public ListNode(int x) {
val = x;
}
}
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
// Create a sentinal/dummy node to start
ListNode returnNode
= new ListNode
(Integer.
MIN_VALUE);
// Create a copy of this node to iterate while solving the problem
ListNode headNode = returnNode;
// Traverse till one of the list reaches the end
while (l1 != null && l2 != null) {
// Compare the 2 values of lists
if (l1.val <= l2.val) {
returnNode.next = l1;
l1 = l1.next;
} else {
returnNode.next = l2;
l2 = l2.next;
}
returnNode = returnNode.next;
}
// Append the remaining list
if (l1 == null) {
returnNode.next = l2;
} else if (l2 == null) {
returnNode.next = l1;
}
// return the next node to sentinal node
return headNode.next;
}
{
// your code goes here
Ideone x = new Ideone();
ListNode l1 = new ListNode(1);
l1.next = new ListNode(2);
l1.next.next = new ListNode(4);
ListNode l2 = new ListNode(1);
l2.next = new ListNode(3);
l2.next.next = new ListNode(4);
ListNode listNode = x.mergeTwoLists(l1, l2);
while(listNode != null) {
System.
out.
print(listNode.
val + " -> "); listNode = listNode.next;
}
}
}