Swapping Elements In A Linked List Java

Because the same linked lists have pointers from each node to the next node, replacing two nodes in the list is not as easy as doing the end (where you have access to the pointer).

An input of an attached list is given, data 1 , and

  • Iterate through the list looking for the node that matches data1 to be swapped (node1), keeping track of the node’s previous node as you iterate (node1Prev)
  • Repeat step 1 looking for the node that matches data2 (giving you node2 and node2Prev)
  • If node1Prev is null, node1 was the head of the list, so set the list’s head to node2
  • Otherwise, set node1Prev‘s next node to node2
  • If node2Prev is null, set the list’s head to node1
  • Otherwise, set node2Prev‘s next node to node1
  • Set node1‘s next node to node2‘s next node
  • Set node2‘s next node to what was node1‘s next node
  • Let's see what are the steps to implement 1 and 2.

    We'll start by configuring node 1 next to the head of the list, and then

    public static void swapNodes(LinkedList list, int data1, int data2) { Node node1 = list.head; Node node2 = list.head; Node node1Prev = null; Node node2Prev = null; while (node1 != null) { if (node1.data == data1) { break; } node1Prev = node1; node1 = node1.getNextNode(); } }

    At the end of this, we have found our matching node, and also saved its previous node, which we will use in the next step.

    Leave a Comment

    Your email address will not be published. Required fields are marked *