Question: package Exercise1; public class SwapNodes { class Node { int data; Node next; public Node(int data) { this.data = data; this.next = null; } }

package Exercise1;

public class SwapNodes {

class Node {

int data;

Node next;

public Node(int data) {

this.data = data;

this.next = null;

}

}

public Node head = null;

public Node tail = null;

public void addNode(int data) {

//Create a new node

Node newNode = new Node(data);

if (head == null) {

head = newNode;

tail = newNode;

} else {

tail.next = newNode;

tail = newNode;

}

}

public void swap(int n1, int n2) {

Node prevNode1 = null, prevNode2 = null, node1 = head, node2 = head;

//Checks if list is empty

if (head == null) {

return;

}

if (n1 == n2)

return;

while (node1 != null && node1.data != n1) {

prevNode1 = node1;

node1 = node1.next;

}

while (node2 != null && node2.data != n2) {

prevNode2 = node2;

node2 = node2.next;

}

if (node1 != null && node2 != null) {

if (prevNode1 != null)

prevNode1.next = node2;

else

head = node2;

if (prevNode2 != null)

prevNode2.next = node1;

else

head = node1;

Node temp = node1.next;

node1.next = node2.next;

node2.next = temp;

} else {

System.out.println("Swapping is not possible");

}

}

public static void main(String[] args) {

SwapNodes list = new SwapNodes();

list.addNode(1);

list.addNode(2);

list.addNode(3);

list.addNode(4);

list.addNode(5);

System.out.println("Original List:");

list.printList();

int n1 = 2, n2 = 4;

System.out.println("After swapping " + n1 + " and " + n2);

list.swap(n1, n2);

list.printList();

}

public void printList() {

Node current = head;

while (current != null) {

System.out.print(current.data + " ");

current = current.next;

}

}

}

Can you please add comments line on my code so I have easier time to explain it? A comment like this //This function does this

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!