Java Challenge - Swap Elements in a Linked List

This community-built FAQ covers the “Swap Elements in a Linked List” code challenge in Java. You can find that challenge here, or pick any challenge you like from our list.

Top Discussions on the Java challenge Swap Elements in a Linked List

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Here’s my solution. (I did the challenge in JavaScript earlier, and then rewrote bits to make it work in Java.
(Originally, I just planned to swap the .data, but this time I changed the .next for the relevant nodes, and I returned the new head node.)
I made some helper methods for getting a node when given its .data, getting the previous node, and printing the list.

Here’s the code … its not pretty, but it works okay.

public class SwapNodes {

  Node head; //this.head

  // constructors
  public SwapNodes() {
    this.head = null;
  }
  public SwapNodes(Node headNode) {
    this.head = headNode;
  }

  Node search(int dataValue) {
    Node current = this.head;
    while (current != null) {
      if (current.data == dataValue) {
        return current;
      }
      // set up for next iteration >> move to next node
      current = current.next;
    }
    return null;
  }

  Node getPreviousNode(Node node) {
    Node current = this.head;
    while (current != null) {
      if (current.next == node) {
        return current;
      }
      // set up for next iteration >> move to next node
      current = current.next;
    }
    return null;
  }

  public static Node swapNodes(Node list, int data1, int data2) {
    if (data1 == data2) {
      return list;
    }
    Node newList = list;
    SwapNodes SwapNodesObj = new SwapNodes(list);
    // get the nodes
    Node node1 = SwapNodesObj.search(data1);
    Node node2 = SwapNodesObj.search(data2);

    Node before1 = null;
    Node before2 = null;
    if (node1 != list) {
      before1 = SwapNodesObj.getPreviousNode(node1);
    }
    if (node2 != list) {
      before2 = SwapNodesObj.getPreviousNode(node2);
    }
    Node after1 = node1.next;
    Node after2 = node2.next;

    // deal with cases when node1 and node2 are adjacent 
    if (after1 == node2) {
      if (before1 != null) {
        before1.next = node2;
      }
      node2.next = node1;
      node1.next = after2;
    }
    else if (after2 == node1) {
      if (before2 != null) {
        before2.next = node1;
      }
      node1.next = node2;
      node2.next = after1;
    }
    // deal with non-adjacent node1 and node2
    else {
      if (before1 != null) {
        before1.next = node2;
      }
      node1.next = after2;
      if (before2 != null) {
        before2.next = node1;
      }
      node2.next = after1;
    }

    // if node1 or node2 is the list (head node)
    if (list == node1) {
      newList = node2;
    }
    else if (list == node2) {
      newList = node1;
    }
    return newList;
  }

  public static void printList(Node linkedList) {
    Node current = linkedList;
    boolean started = false;
    while (current != null) {
      if (started) {
        System.out.print(" -> ");
      }
      else {
        started = true;
      }
      System.out.print(current.data);
      // set up for next iteration >> move to next node
      current = current.next;
      if (current == linkedList) {
        System.out.print(" -> (Circular List)");
        break;
      }
    }
    System.out.println("");
  }

  public static void main(String[] args) {
    Integer[] testArr = {1, 2, 3, 4, 5, 6};
    Node list = Node.makeLinkedList(testArr);
    printList(list);
    Node swapped = swapNodes(list, 2, 5);
    printList(swapped);
  }
}

I found it odd to use the head node as the list instead of having a separate list object where the .head would be the head node.

This is my Java solution. You can use the already defined function :slight_smile:

public static Node swapNodes(Node list, int data1, int data2) {
ArrayList arr = new ArrayList();

while(list != null){
 
  if(list.data == data1){//list=1 list.next=2
    arr.add(data2);
  } else if(list.data == data2){//list=4
    arr.add(data1);
  }else{
    arr.add(list.data);
  }
  list=list.next;
}
Integer[] result = arr.toArray(new Integer[arr.size()]);

return Node.makeLinkedList(result);

}