How to swap nodes between two Doubly Linked List completely

Solution for How to swap nodes between two Doubly Linked List completely
is Given Below:

Hey everyone I am trying to swap two nodes between two Doubly Linked Lists completely (value and address too). Only the Nodes that are at the same positions can be swapped between i.e a Node at position 2 can only be swapped by the Node in position 2 in the other LinkedList. Consider the following example of 2 LinkedLists:

``````815 102 162 524
622 101 830 754
``````

Let’s say we want to swap the third elements which would be 162 and 830. After swapping the LinkedLists becomes:

``````815 102 830 524
622 101 162 754
``````

I have tried the following code but it doesn’t swap for the previous elements.

``````void swapNodes(Node* firstListNode, Node* secondListNode)
{
Node* FirstNodeNext = firstListNode->next;
Node* FirstNodePrev = firstListNode->previous;
Node* SecondNodeNext = secondListNode->next;
Node* SecondNodePrev = secondListNode->previous;

if (firstListNode->previous == NULL && secondListNode->previous == NULL)
{
firstListNode->next = SecondNodeNext;
secondListNode->next = FirstNodeNext;
}
// if the nodes are tails
else if(firstListNode->next == NULL && secondListNode->next == NULL)
{
firstListNode->previous = SecondNodePrev;
secondListNode->previous = FirstNodePrev;
}
else
{
firstListNode->next = SecondNodeNext;
firstListNode->previous = SecondNodePrev;

secondListNode->next = FirstNodeNext;
secondListNode->previous = FirstNodePrev;
}
}
``````

How can I accomplish this task?

The else if doesn’t swap the previous elements, for example if we pass the value 524, and 754 to the function it should be the tail and execute the else if statement as it has no next nodes.

After the swapping it should be:

``````815 102 162 754
622 101 830 524
``````

The code doesn’t swap the previous nodes.

I think you are losing the references for swapping in other linkedlist, below is the working code snippet for the same in java. Please note, i’m assuming here that both of the linkedlist is of same length.

``````public class Application {

static class Node{
private int value;
private Node prev;
private Node next;

public Node(int value){
this.value = value;
}

public void print(){
for(Node node=this; node!=null; node = node.next){
System.out.print(node.value + "->");
}
System.out.println();
}
}

public static void main(String[] args) {

}

System.out.println("Swaping node at index : "+index);
if(index == 0){
return;
}

}

if(linkedList1Ref.next != null && temp2Nxt != null) {