Merge Two Sorted Double LinkedLists--Java

#1

I am trying to do the merge Two sorted Double LinkedLists and here is what I got so far correct me if I am wrong

public static ListNode mergeSortedDoubleLinkedList(ListNode L1,ListNode L2){
ListNode dummyHead=new ListNode(0,null,null);

ListNode current=dummyHead,p1=L1,p2=L2;
while(p1!=null || p2!=null){
if(p1.data<p2.data){
current.next=p1;
current.prev=p1.prev;
p1=p1.next;
p1.prev=current;
}
else
{
current.next=p2;
current.prev=p2.prev;
p2=p2.next;
p2.prev=current;
}
current.prev=current;
current=current.next;
}
current.next=p1!=null?p1:p2;
return dummyHead.next;
}

0 Likes

#2

Sorry I cannot understand the code due to formatting. Also, we don’t have this problem in the book but you shall be able to use the problem of merging two sorted list so you shall use that to check.

0 Likes

#4
Honestly I couldn’t format the code on the original discussion post so I have just posted as it is. However the problem that I asked was a variant on merge sorted linked lists from the book. What I was trying to do above was to update the previous nodes since its a doubly linked list something like

if(p1.data<p2.data){
current.next=p1;
current.prev=p1.prev;
p1=p1.next;
p1.prev=current;
}
else
{
current.next=p2;
current.prev=p2.prev;
p2=p2.next;
p2.prev=current;
}

Is this the right way to update the previous pointers? Any helps would be greatly appreciated :smiley: By the way Thanks for taking time to reply for my post.

0 Likes

#5

I would suggest you to write a test for yourself on this to verify this.

0 Likes