Search code examples
javanodesswap

Swap three elements in LinkedBag. i.e. ABC==BCA


I'm attempting to write a method that will swap the first 3 elements in a LinkedBag and return true if successful. If the original bag is "1,2,3,4", then the swapped bag should be, "2, 3, 1, 4". As you can see, my output is incorrect and I feel stuck. Any help or solutions would be much appreciated. Thank you in advance!

public boolean swap123() {

    if (this.getCurrentSize() < 3)
        return false;
    else {
        Node node1 = firstNode;
        Node node2 = firstNode.next;
        Node node3 = firstNode.next.next;
        Node temp = node3;
        Node temp2 = firstNode;


        node1.data = node2.data;

        node2.data = temp.data;

        node3.data = temp2.data;


        return true;
    }
}

Original test bag: 1, 2, 3
Expected Output: 2, 3, 1
Actual Output: 2, 3, 2


Solution

  • temp2 and node1 are both pointers to firstnode

    node1.data = node2.data; //sets the data of firstnode to the data of node2
    
    node3.data = temp2.data; // sets the data of node 3 to the data of firstnode( which has become 2)
    

    You can't swap the data with pointers only, you need an temp Object to hold the data. Or you change the linking and keep the data.