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

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!