1. Engineering
  2. Computer Science
  3. javas question reverse the list quotin placequot without creating any...

Question: javas question reverse the list quotin placequot without creating any...

Question details

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 ();

  

}

}

Solution by an expert tutor
Blurred Solution
This question has been solved
Subscribe to see this solution