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);

}

Keeping it simple and to the point.

public class SwapNodes {

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

  public static Node swapNodes(Node list, int data1, int data2) {
    Node head = list;
    while(head != null){
      if(head.data == data1){
        head.data = data2;
      } else if(head.data == data2){
        head.data = data1;
      }
      head = head.next;
    }
    return list;
  }
}

The easy method to this challenge would be to just swap the data in each of the nodes, but I chose to answer the spirit of the question instead for practice.

public class SwapNodes {

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

  public static Node swapNodes(Node list, int data1, int data2) {
    // grab first node + save swapping info
    Node first = getNode(list, data1);
    Node before1 = getNodeBefore(list, data1);
    Node firstNextSave = first.next;

    // grap second node + save swapping info
    Node second = getNode(list, data2);
    Node before2 = getNodeBefore(list, data2);
    Node secondNextSave = second.next;
    
    // swap in the second
    before1.next = second;
    second.next = firstNextSave;
    // swap in the first
    before2.next = first;
    first.next = secondNextSave;

    printList(list);
    return list;
  }

  public static Node getNodeBefore(Node list, int value) {
    Node current = list;

    while (current.next != null) {
      if (current.next != null) {
          if (current.next.data == value) {
             return current;
          }
          else {
            current = current.next;
          }
      }
    }

    return null;
  }

  public static Node getNode(Node list, int value) {
      return getNodeBefore(list, value).next;
  }

  // helper test function to check the list
  public static void printList(Node list) {
    while (list.next != null) {
      System.out.print(list.data + " -> ");
      list = list.next;
    }
    System.out.print(list.data);
    System.out.println();
  }
}

Why this pass 4/5, where is the problem?

public class SwapNodes {

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

  public static Node swapNodes(Node list, int data1, int data2) {
    if(data1 == data2){
      return null;
    }
    Node head = list;
    Node first = head;
    Node second = head;
    Node beforeFirst = null;
    Node beforeSecond = null;

    while(first != null){
      if(first.data == data1){
        break;
      }
      beforeFirst = first;
      first = first.next;
    }

    while(second != null){
      if(second.data == data2){
        break;
      }
      beforeSecond = second;
      second = second.next;
    }

    if(first == null || second == null){
      return null;
    }

    if(beforeFirst == null){
      head = second;
    }else{
      beforeFirst.next = second;
    }

    if(beforeSecond == null){
      head = first;
    }else{
      beforeSecond.next = first;
    }

    Node temp = first.next;
    first.next = second.next;
    second.next = temp;

    return head;
  }
}

I haven’t quite been able to pin down why this is the issue, but it seems your code throws an exception if one of the nodes you try to swap is the first node in the linked list. i.e. using swapNodes(list, 1, 5); in place of swapNodes(list, 2, 5);

Output:

1
6
Exception in thread "main" java.lang.NullPointerException
	at SwapNodes.main(SwapNodes.java:9)

My guess is that somewhere around line 39 or 45 where you handle one of the previous value being null, you haven’t taken something into account that is throwing off the algorithm. One of the tests running behind the scenes must take this edge case into account.

EDIT: Forgot to mention I added this at the bottom of main() to print the values along the way — the error doesn’t show without it:

System.out.println(list.data);
System.out.println(list.next.data);
System.out.println(list.next.next.data);
System.out.println(list.next.next.next.data);
System.out.println(list.next.next.next.next.data);
System.out.println(list.next.next.next.next.next.data);
1 Like

Got it!

Hint

In main() you call .swapNodes(), which returns a reference to the new head of the list. Where is this returned value going?

Answer

Nowhere!! Since the function is called without being assigned to a variable, the computed value ends up getting tossed. The result of calling .swapNodes() should be reassigned to the list variable.

But wait, there’s more! That still only returns 4/5

Hint

Speaking of return values, you have a second return statement in your function that returns null. What is the implication of this, considering that this value gets reassigned to list in main()?

Answer

This overwrites the entire list in main() with null!! Bye list!
To fix this, instead of returning null if the two data are equal, return a reference to the original list that was passed in.

After addressing those two issues, I’m getting all tests pass!

Hope that helps, happy coding :smile:

1 Like

Yes, function return new correct head so you need to take return node from function and use it, this way it work.

public static void main(String[] args) {
    Integer[] testArr = {1, 2, 3};
    Node list = Node.makeLinkedList(testArr);
    Node newHead = swapNodes(list, 1, 3);
    System.out.println(newHead.data);
    System.out.println(newHead.next.data);
    System.out.println(newHead.next.next.data);
  }

But i think test don’t work that way so we need to change something here, will update when find solution.

Thanks man, great explanation, now all test work. Good catch!

Blockquote This overwrites the entire list in main() with null !! Bye list!

This is not 100% true, old list is still here, it does not overwrites it just give new reference with null.
That is if you use 2 different variable, but if you put the return of function in list variable, yes you will lose the list.

Lost list:

Node list = Node.makeLinkedList(testArr);
list = swapNodes(list, 1, 3);

Not lost list:

Node list = Node.makeLinkedList(testArr);
Node newHead = swapNodes(list, 1, 3);

Anyway I agree it’s better solution to return list and make it safer and smarter!

New working code!
public class SwapNodes {

  public static void main(String[] args) {
    Integer[] testArr = {1, 2, 3};
    Node list = Node.makeLinkedList(testArr);
    list = swapNodes(list, 1, 3);
    System.out.println(list.data);
    System.out.println(list.next.data);
    System.out.println(list.next.next.data);
  }

  public static Node swapNodes(Node list, int data1, int data2) {
    if(data1 == data2){
      return list;
    }
    Node head = list;
    Node first = head;
    Node second = head;
    Node beforeFirst = null;
    Node beforeSecond = null;

    while(first != null){
      if(first.data == data1){
        break;
      }
      beforeFirst = first;
      first = first.next;
    }

    while(second != null){
      if(second.data == data2){
        break;
      }
      beforeSecond = second;
      second = second.next;
    }

    if(first == null || second == null){
      return list;
    }

    if(beforeFirst == null){
      head = second;
    }else{
      beforeFirst.next = second;
    }

    if(beforeSecond == null){
      head = first;
    }else{
      beforeSecond.next = first;
    }

    Node temp = first.next;
    first.next = second.next;
    second.next = temp;

    list = head;

    return head;
  }
}
1 Like