Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is my method to swap two adjacent elements by adjusting only the links (and

ID: 3842796 • Letter: T

Question

This is my method to swap two adjacent elements by adjusting only the links (and not the data) using a single linked list. But when I run the test program it is printing the list without the swap. Any advice or help as to what i am doing wrong would be appreciated.

Notes: beforep is an input parameter that represents the node before the two adjacent nodes that are to be swapped.

public class Problem1Swapping {

    public static void swapWithNext(Node beforeP) {
        Node p; //First Node to be swapped
        Node afterP;//Second Node to be swapped

        p = beforeP.next;
        afterP = p.next;

        p.next = afterP.next;
        beforeP.next = afterP;
        afterP.next = p;
    }

}

//Provided Node class to use for problem 1
    public class Node {

        public Object data;
        public Node next;

        public Node(Object data, Node next) {
            this.data = data;
            this.next = next;
        }
      
        @Override
        public String toString(){
            return this.data + "";         
        }
    }

public class Problem1SwappingTester {
  
    public static void main(String args[]){
      
        Node node1 = new Node(25, null);
        Node node2 = new Node(35, node1);
        Node node3 = new Node(46, node2);
        Node node4 = new Node(57, node3);
        Node node5 = new Node(68, node4);

        LinkedList list1 = new LinkedList();
        list1.add(node5);
        list1.add(node4);
        list1.add(node3);
        list1.add(node2);
        list1.add(node1);
      
        System.out.println(list1);
        Problem1Swapping.swapWithNext(node3);
        System.out.println(list1);
    }   
}

OUTPUT:

run:
[68, 57, 46, 35, 25]
[68, 57, 46, 35, 25]
BUILD SUCCESSFUL (total time: 0 seconds)

Explanation / Answer

--> Problem1Swapping.swapWithNext(node3); // Here you are just sending node3.. So you cant access the list inside the Problem1Swapping.swapWithNext() function.

--> You are printing the same list twice, and thats why you got the same output.

--> Send 2 parameters to Problem1Swapping.swapWithNext(). The parameters are list and node3.

--> Iterate the list till you find node3, after that do the swap. Your swap code is correct.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote