To swap two nodes of a linked list in Java, you can update the links between the nodes to point to each other, instead of the nodes they were previously pointing to.
Here's an example of how to swap two nodes A
and B
of a linked list in Java:
class Node { int data; Node next; } void swapNodes(Node A, Node B) { // Store the next nodes of A and B Node tempA = A.next; Node tempB = B.next; // Update the next nodes of A and B to point to each other A.next = tempB; B.next = tempA; }
In this example, the swapNodes
function takes two Node
objects as arguments and swaps their positions in the linked list by updating their next
pointers. The tempA
and tempB
variables are used to store the next nodes of A
and B
before updating the next
pointers, so that the links between the rest of the nodes are not lost.
To use this function to swap two nodes of a linked list, you can call it with the nodes as arguments:
Node A = new Node(); A.data = 1; Node B = new Node(); B.data = 2; A.next = B; B.next = null; swapNodes(A, B);
This will swap the positions of the nodes A
and B
in the linked list, so that A
comes after B
and B
comes after A
.
You can find more information about linked lists and how to work with them in Java in the Java documentation.