I have tried to merge two sorted lists into one and print that list using display method. But I am getting, I am getting this output:
-1 --> -21 --> 0 --> 2 --> 3 --> 5 --> 44 --> null
instead of:
-21 --> 0 --> 2 --> 3 --> 5 --> 44 --> null
Why am I getting this extra -1 before? I know that I have in line 15 ListNode dummy= new ListNode(-1); which I have initialized with -1. Is it the same -1 that I am getting? How do I skip this?
Here is my code :
public class Mergelists {
private static ListNode head;
private static class ListNode{
int val;
ListNode next;
public ListNode(int val){
this.val= val;
this.next= null;
}
}
public static ListNode merge(ListNode l1, ListNode l2){
ListNode dummy = new ListNode(-1);
head = dummy;
while (l1 != null && l2 != null){
if (l1.val<l2.val){
dummy.next=l1;
l1=l1.next;
}
else
{
dummy.next=l2;
l2=l2.next;
}
dummy=dummy.next;
}
if (l1 !=null)
dummy.next=l1;
if (l2 !=null)
dummy.next=l2;
return head.next;
}
public static void display() {
ListNode current = head;
while(current != null) {
System.out.print(current.val + " --> ");
current = current.next;
}
System.out.print("null");
}
public static void main(String[] args) {
ListNode head1 = new ListNode(-21);
head1.next = new ListNode(3);
head1.next.next = new ListNode(5);
// -21->3->5 LinkedList created
ListNode head2 = new ListNode(0);
head2.next = new ListNode(2);
head2.next.next = new ListNode(44);
// 0->2->44 LinkedList created
merge(head1, head2);
display();
}