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

This works but the professor wants me to walk the list like i don\'t know what\'

ID: 3534855 • Letter: T

Question

This works but the professor wants me to walk the list like i don't know what's on it; find nodes m and n, and then swap them instead of hardcoding them. Nodes M and N can be anythng.




import java.util.*;
public class DynamicNode
{
private Object info;
private DynamicNode next;


public DynamicNode(Object x, DynamicNode n)
{
info = x;
next = n;
}

public Object getInfo()
{
return info;
}

public DynamicNode getNext()
{
return next;
}

public void setInfo(Object x)
{
info = x;
}

public void setNext(DynamicNode n)
{
next = n;
}
}





import java.util.*;
public class Swap
{
public static void main(String[] args)
{
DynamicNode p = new DynamicNode(null, null);

DynamicNode Node1 = new DynamicNode("a", null);
DynamicNode Node2 = new DynamicNode("A", null);
DynamicNode Node3 = new DynamicNode("b", null);
DynamicNode Node4 = new DynamicNode("B", null);
DynamicNode Node5 = new DynamicNode("abAB", null);

DynamicNode list = null;
Node1.setNext(Node2);
Node2.setNext(Node3);
Node3.setNext(Node4);
Node4.setNext(Node5);



list=Node1;
System.out.println("Original list");
p=list;

for(int i = 0; i < 5; i++)
{
System.out.println(p.getInfo());
p=p.getNext();
}

System.out.println("New List....b and A are switched");
p=list;
Node1.setNext(Node3);
Node2.setNext(Node4);
Node3.setNext(Node2);
Node5.setNext(Node5);
for(int i = 0; i < 5; i++)
{
System.out.println(p.getInfo());
p = p.getNext();
}

}
}

Explanation / Answer

Here is my last attempt. Expecting a good rating after so much of work (at least better than the above :D )


Here goes the solution.


Firstly and most importantly, you need to create an array of the nodes, not directly hardcode them since you need to traverse the list later, which would not be possible if you hardcode them.


Let the nodes array be nodes[10];

Let us first loop to get the mth and the nth nodes.


Input m and n from the user

for(i=0;i<no_nodes;i++)

{

if(i==m-1)

{

//we have found the mth node.

//Save its index

index_m=i;

}

if(i==n-1)

{

//we have found the mth node.

//Save its index

index_n=i;

}

}


//Now we swap the elements.

Let m>n


the next of m becomes the next of n and vice versa.

This can be done by:


m.setnext(n.next)

n.setnext(m.next)


Also the prev of m and n now point to the swapped values.


m.prev.next=nodes[n];

n.prev.next=nodes[m];


This is all I can think of now :) Hope it helps you.


Cheers!



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