Question
Java's question reverse the list in place... without creating any new nodes Here is the code is given: public class MyLinked { static class Node
Java's question
reverse the list "in place"... without creating any new nodes
Here is the code is given:
public class MyLinked {
static class Node {
public Node() { }
public double item;
public Node next;
}
int N;
Node first;
public MyLinked () {
first = null;
N = 0;
}
public void add (double item) {
Node newfirst = new Node ();
newfirst.item = item;
newfirst.next = first;
first = newfirst;
N++;
}
public void reverse () {
//Here need to do
}
private static void print (String s, MyLinked b) {
StdOut.print (s + ": ");
for (Node x = b.first; x != null; x = x.next)
StdOut.print (x.item + " ");
StdOut.println ();
}
private static void print (String s, MyLinked b, double i) {
StdOut.print (s + ": ");
for (Node x = b.first; x != null; x = x.next)
StdOut.print (x.item + " ");
StdOut.println (": " + i);
}
private static void testReverse () {
MyLinked b = new MyLinked ();
b.reverse ();
print ("reverse empty", b);
b.add (1);
print ("singleton", b);
b.reverse ();
print ("reverse singleton", b);
b.add (2);
print ("two", b);
b.reverse ();
print ("reverse two", b);
b.reverse ();
print ("reverse again", b);
for (double i = 3; i < 7; i++) {
b.add (i);
b.add (i);
}
print ("bigger list", b);
b.reverse ();
print ("reversed", b);
}
public static void main (String args[]) {
testReverse ();
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started