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

1) Create a new ReverseIterator and a method that returns one that visits list e

ID: 3749757 • Letter: 1

Question

1) Create a new ReverseIterator and a method that returns one that visits list elements in reverse order. Because this is a singly linked list, this iterator will perform poorly. That is desirable for our purposes.

2) Write a Tester1 class that demonstrates that your modifications function correctly. Simply test add(T value), remove() and remove(int index). Make sure that size() returns the correct value after adds and removes. Make sure the forward iterator still works, including your new remove() method. Make sure your new reverse iterator works correctly.

3) Write a Tester2 class that shows that your new add(T value) method operates in constant time, rather than linear as in the provided code. Show that your reverse iterator operates in quadratic time.

Code Provided:

LinkedList.java

import java.util.Iterator;

public class SinglyLinkedList<T> implements Iterable<T>{

// since this is an inner class (not a static nested class), we can access

// T

private class Node

{

T value;

Node next;

Node(T value, Node next)

{

this.value=value;

this.next=next;

}

Node() { }

}

private int count; // number of items in the list

private Node head;        // pointer to dummy node at head of list

private Node tail;           // Performs tail operations in constant time

  public SinglyLinkedList()

{

//head = new Node(); // dummy node

}

/**

   * Add a value to the end of the list

   * @param value the value to be added

   * This performs linearly with respect to the length of the list.

   * TOOD: Modify the list, and this method, to make this a constant

   * operation

*/

void add(T value) {

/* Node curs=head;

while (curs.next != null)

{

curs=curs.next;

}

curs.next = new Node(value,null);

count++;*/

//CONSTANT TIME ADDITION

Node newNode = new Node(value, null);

  if (head == null)

   {

       head = tail = newNode;

   }

   else {

       tail.next = newNode;

   }

}

void removeLast()

{

  if(head == null)

{

  return;

}

  if(head == tail)

{

head = tail = null;

return;

}

Node curs = head;

  while(curs.next != null && curs.next.next != null)

{

curs = curs.next;

}

curs.next = null;

tail = curs; //updating tail to new last node

}

  void remove(int index)

{

if(index == 0)

{

head = head.next;

}

else

{

Node node = findNode(index - 1);

if(node.next != null && node.next.next != null)

{

node.next = node.next.next;

}

}

}

/**

   * Add a value to the list at position index

   * @param index the desired location

   * @param value the value to be added

   *

   * Note: this throws an exception if index is invalid

   *

   * Food for thought: How does the performance of this method depend on index?

   */

  

void add(int index, T value)

{

Node c=findNode(index);

  

c.next=new Node(value, c.next);

  

count++;

}

/**

   @index the index of the desired list value

   @return the value in the list at the index'th position

   Throws exception if index is invalid

*/

  

T get(int index)

{

Node c=findNode(index);

  

return c.next.value;

}

  

/**

   * @return the number of items in this list

   */

  

int size()

{

return count;

}

  

/**

   * Returns a Node whose .next member is (or would be, in the case of

   * index==count) the index'th Node in the list

   *

   * Throws an exception if the index is not valid

   *

   * @param index the index of the desired Node

   * @return the Node whose next is the index'th

   */

  

private Node findNode(int index)

{

// Notice how the use of a 'dummy' node at the head makes this logic

// simpler

Node curs=head;

  

int p = 0;

if (index < 0)

{

throw new RuntimeException("invalid index: " + index);

}

while (p < index && curs != null)

{

curs=curs.next;

p++;

}

if (curs == null)

{

throw new RuntimeException("invalid index: " + index);

}

return curs;

}

/**

   Implements java.lang.Iterable<T>

*/

  

public java.util.Iterator<T> iterator()

{

return new ForwardIterator();

}

private class ForwardIterator implements java.util.Iterator<T>

{

// This is legal since it's a proper inner class (not a static nested

// class)

Node curs = head;

public boolean hasNext()

{

return curs.next != null;

}

// Note: this method has undefined behavior if hasNext() return false

public T next()

{

curs = curs.next;

  

return curs.value;

}

// TODO: add a remove() method -- see the java.util.Iterator documentation

@Override

  

public void remove()

{

   if (curs != null)

   {

       if (curs == head)

       {

           head = head.next;

       }

          

       else if (curs.next != null)

           {

           curs.next = curs.next.next;

           }

   }

}

}

// TODO: Write a ReverseIterator inner class, along with a public method

// for returning it. Normally you would only have such a thing on a

// doubly linked list, but we're writing one to analyze its performance.

Tester1.java

public class Tester1 {

public static void main(String[] args)

{

// See the SinglyLinkedList class in action ...

SinglyLinkedList<String> sl1 = new SinglyLinkedList<>();

sl1.add("a");

sl1.add("b");

sl1.add("c");

sl1.add(1, "in the middle!");

sl1.add(0, "at the beginning");

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

  

for (String s : sl1)

{

System.out.println(s);

}

// // Equivalent code using an explicit iterator

//

// java.util.Iterator<String> it = sl1.iterator();

// while (it.hasNext())

// {

// System.out.println(it.next());

// }

  

// // Somewhat equivalent code using the get() method

//

// for (int i=0; i<sl1.size(); i++)

// {

// System.out.println(sl1.get(i));

// }

// Analyze the performance of the .add() method

System.out.println();

System.out.println("now some timing tests...");

System.out.println();

  

for (long N=10000; N<100000; N*=2)

{

long start = System.nanoTime();

addN(N);

long end = System.nanoTime();

System.out.println("calling add() " + N + " times took " + (end-start)/1e6 + " ms");

}

  

   sl1.add(2,"35");

   sl1.add(1,"355");

      

   for (String s :sl1) {

       System.out.println(s);

   }

      

   sl1.remove(3);

      

   for (String s: sl1) {

       System.out.println(s);

   }

}

public static SinglyLinkedList<Long> addN(long N)

{

SinglyLinkedList<Long> slist = new SinglyLinkedList<>();

for (long i=0; i<N; i++)

{

slist.add(i);

}

return slist;

}

}

Tester2.java

public class Tester2 {

  

   public static void main(String[] args)

   {

       System.out.println();

       System.out.println("now some timing tests...");

       System.out.println();

      

       for (long N = 10000; N < 100000; N *= 2)

       {

           long start = System.nanoTime();

          

           addN(N);

          

           long end = System.nanoTime();

          

           System.out.println("calling add()" + N + " times took " + (end -start) / 1e6 + " ms");

          

       }

   }

   public static SinglyLinkedList<Long> addN(long N)// Auto-generated method stub

   {

       SinglyLinkedList<Long>slist = new SinglyLinkedList<>();

      

       for (long i = 0; i < N; i++)

       {

           slist.add(i);

       }

       return slist;

      

   }

}

Explanation / Answer

LinkedList.java

import java.util.Iterator;

import java.util.LinkedList;

import java.util.List;

public class SinglyLinkedList<T> implements Iterable<T>

{

public static void main(string[] args)

{

List<String> ReverseIterator = new LinkedList<>();

list.elements=newlinkedlist

// since this is an inner class (not a static nested class), we can access

// T

private class Node

{

T value;

Node next;

Node(T value, Node next)

{

this.value=value;

this.next=next;

}

Node() { }

}

private int count; // number of items in the list

private Node head; // pointer to dummy node at head of list

private Node tail; // Performs tail operations in constant time

public SinglyLinkedList()

{

//head = new Node(); // dummy node

}

while(namesIterator.hasNext()){

System.out.println(namesIterator.next());//to print the iterated elements

}

}

//Add a value to the end of the list

public iterated data values() {

ArrayList<float>iteratedvalue = new ArrayList<>(); //declaration of iterated value in an array

for(int i=0;i<values.size(); i++)

{

system.out.println(iterated value);

system.out.println(iterated value.size());

return null;

//@param value the value to be added

public void addNewValue(String union, String em, String pw){

addparameters = row.createValue(0);//adding parameters over the value

addparameters.setIteratedValue(un);

//This performs linearly with respect to the length of the list.

}

//TOOD: Modify the list, and this method, to make this a constant

// Main method where program execution begins

public static void main(String[] args) {

staticMethod();

Methods object = new Methods();

object.nonStaticMethod();

}

// Static method

static void staticMethod() {

System.out.println("Static method can be called without creating object");

}

//for the corresponding iterated value

// Non static method

void nonStaticMethod() {

System.out.println("Non static method must be called by creating an object");

}

void add(T value) {

/* Node curs=head;

while (curs.next != null)

{

curs=curs.next;

}

curs.next = new Node(value,null);

count++;

//modification of list

public classModificationException{

public static void main(String args[]) {

List<String> myList = new ArrayList<String>();

myList.adding("1");

myList.adding("2");

myList.adding("3");

Iterator<String> iter = myList.iterator(); //modification of list

while (iter.hasNext()) {

String value = iter.next();

System.out.println("List Value:" + value);

if (value.equals("3"))

myList.remove(value);

}

//modification over the itered values

//CONSTANT TIME ADDITION

Node newNode = new Node(value, null);

if (head == null)

{

head = tail = newNode;

}

else {

tail.next = newNode;

}

}

void removeLast()

{

if(head == null)

{

return;

}

if(head == tail)

{

head = tail = null;

return;

}

Node curs = head;

while(curs.next != null && curs.next.next != null)

{

curs = curs.next;

}

curs.next = null;

tail = curs; //updating tail to new last node

}

void remove(int index)

{

if(index == 0)

{

head = head.next;

}

else

{

Node node = findNode(index - 1);

if(node.next != null && node.next.next != null)

{

node.next = node.next.next;

}

}

}

//Add a value to the list at position index

ArrayList<Integer> arrlist = new ArrayList<Integer>(5);//adding value to the list

// have to use add() method to add elements in the list

arraylist.add(13); //lets say an integer to add in ist

arraylist.add(24);

arraylist.add(4,100); //adding elements and the position at list

//@param index the desired location

//@param value the value to be added

public Adding parameterValues() {

ArrayList<Float> iterValue = new ArrayList<>();

for (int a = 0; a<itervalue.size(); a++) //adding parameter index the desired location

{

IterValue.add(size.get(limit).getIter()); //addind iter value

}

System.out.println(iterValue);

System.out.println(IterValue.size());

return null;

}

Note: this throws an exception if index is invalid

If (invalid!)

MyClass obj = null;

try {

logger.information("the field is " + obj.field,itervalue);

} catch(Exception e) {}

logger.information("the field is " + obj.field,itervalue);

} throw(Exception e) {}

//throws exception of invalid

//Food for thought: How does the performance of this method depend on index?

1.It Includes cost limit for performance management.

2.Create internal activity reports.

3.Set performance requirements in the specifications.

void add(int index, T value)

{

Node c=findNode(index);

c.next=new Node(value, c.next);

count++;

}

// @index the index of the desired list value

while (index.NextLine()) {

String data = Index.nextLine();

ArrayData.add(i, data);

if (Indexvalue.contains("ID: ")) {

indexData.add(a, data);

indexData.set(a, (idData.get(a).replaceAll("[\D]", "")));

a++;

b++;

}

i++;

idIndex.add(b, Integer.toString(i));

}

//@return the value in the list at the index'th position

public int ( Integer number ) {

int index = 0;

int position = 0;

while (position <= array.length && number == array[position]){

index = index + 1; //to determine the index position

if( index <= array.length ){

index = position ;

} else {

index = -1;

}

}

return index ;   

}

// Throws exception if index is invalid

if (n < 0) {

throw new Exception("n must be a positive integer");

//it should be a positive integer

}

get.index()

T get(int index)

{

Node c=findNode(index);

return c.next.value;

}

//@return the number of items in this list

List<String> ls=new ArrayList<String>();

ls.adding("one");

ls.adding("Three");

//returning the items in the list

int size()

{

int sizeOfList=ls.size();

System.out.println("Size of List :"+sizeOfList);

return count;

}

// Returns a Node whose .next member is (or would be, in the case of

if (items.get(left) != null) {

current.left = new TreeNodeRightMost(null, items.get(left), null);

queue.add(current.left);

}

if (right < items.size() && items.get(right) != null) {

current.right = new TreeNodeRightMost(null, items.get(right), null);

queue.add(current.right);

//index==count) the index'th Node in the list

public TreeNodeRightMost getRoot(Nth) {

return root;

}

//index in the nth node

// Throws an exception if the index is not valid

if(invalid!)

if (n < 0) {

throw new Exception("n must be a positive integer");

}

// @param index the index of the desired Node

final TreeNodeIndex root = tree.getRoot(); //passing parameters

if (root == null) throw new IllegalStateException(" empty tree is not permitted");

Queue<TreeNodeRightMostIndex> queue = new LinkedList<>();

Queue<TreeNodeRightMostIndex> queueNext = new LinkedList<>();

queue.add(root);

//@return the Node whose next is the index'th

if (node.item == val) {

if (queue.size() > indexth) { //returning node in index

return queue.poll().item;

} else {

return node;

}

private Node findNode(int index)

{

// Notice how the use of a 'dummy' node at the head makes this logic

simpler

Node curs=head;

int p = 0;

if (index < 0)

{

throw new RuntimeException("invalid index: " + index);

}

while (p < index && curs != null)

{

curs=curs.next;

p++;

}

if (curs == null)

{

throw new RuntimeException("invalid index: " + index);

}

struct node *temp = node_ptr->next; //using dummy nodes to make it simpler

node_ptr->data = temp->data;

node_ptr->next = temp->next;

free(temp);

return curs;

}

Implements java.lang.Iterable<T>

  

public java.util.Iterator<T> iterator()

{

return new ForwardIterator();

}

private class ForwardIterator implements java.util.Iterator<T>

{

// This is legal since it's a proper inner class (not a static nested

// class)

Node curs = head;

public boolean hasNext()

{

outerClass.NestedClass nestedObject =

new OuterClass.NestedClass();

return curs.next != null;

}

// Note: this method has undefined behavior if hasNext() return false

public T next()

{

curs = curs.next;

return curs.value;

}

// TODO: add a remove() method -- see the java.util.Iterator documentation

@Override

void show() { System.out.println("Child's show()"); {

Parent obj1 =new Parent();

obj1.show(); //using polymorphisn

Parent obj2 = new Child();

obj2.show();

}

public void remove()

{

if (curs != null)

{

if (curs == head)

{

head = head.next;

}

  

else if (curs.next != null)

{

curs.next = curs.next.next;

}

}

}

}

// TODO: Write a ReverseIterator inner class, along with a public method

public class ReverseIterator {

public static void main(String[] args) {

inner class = new IterData();

for(Data dat : reverseIter){

System.out.println(data);

}

// for returning it. Normally you would only have such a thing on a

// Generate an iterator

//Start it just after the last element.

ListIterator li = a.listIterator(a.size());

// Iterate in reverse.

while(li.hasPrevious()) {

System.out.println(li.previous());

}

// doubly linked list, but we're writing one to analyze its performance.

Tester1.java

public class Tester1 {

public static void main(String[] args)

{

// See the SinglyLinkedList class in action ...

SinglyLinkedList<String> sl1 = new SinglyLinkedList<>();

sl1.add("a");

sl1.add("b");

sl1.add("c");

sl1.add(1, "in the middle!");

sl1.add(0, "at the beginning");

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

  

for (String s : sl1)

{

System.out.println(s);

}

//Equivalent code using an explicit iterator

void forLoopWithIntegerIndex(){

indexTitle("Normal for loop.");//using explicit iteration

for(int index=0; index < NAMES.size(); ++index){

log(NAMES.get(index));

}

// java.util.Iterator<String> it = sl1.iterator();

Set<String> Integers = new LinkedListSet<>();

while (iter.hasNext())

while(iter.hasNext()){

if (iter.next().trim().length() == 0){

//this only works if the collection supports 'remove'

iter.remove();

}

}

System.out.println(it.next());

return();

}

//Somewhat equivalent code using the get() method

void indexData(StringData) {

String[] IndexResult =data value;

this.setInteger(indexResult[0]);

this.setMonth(indexResult[1]);

public String toString() {

return "y =" + year + ", m =" + month + ",...

}

for (int i=0; i<sl1.size(); i++)

{

System.out.println(sl1.get(i));

}

// Analyze the performance of the .add() method

public class ArrayListDemo {

public static void main(String[] args)

{

  

// create an empty array list with an initial capacity

ArrayList<Integer> arrlist = new ArrayList<Integer>(5);

arrlist.add(12);

arrlist.add(24);

arrlist.add(29);

System.out.println();

System.out.println("now some timing tests...");

System.out.println();

  

for (long N=10000; N<100000; N*=2)

{

long start = System.nanoTime();

addN(N);

long end = System.nanoTime();

System.out.println("calling add() " + N + " times took " + (end-start)/1e6 + " ms");

}

  

sl1.add(2,"35");

sl1.add(1,"355");

  

for (String s :sl1) {

System.out.println(s);

}

  

sl1.remove(3);

  

for (String s: sl1) {

System.out.println(s);

}

}

public static SinglyLinkedList<Long> addN(long N)

{

SinglyLinkedList<Long> slist = new SinglyLinkedList<>();

for (long i=0; i<N; i++)

{

slist.add(i);

}

return slist;

}

}

Tester2.java

public class Tester2 {

  

public static void main(String[] args)

{

System.out.println();

System.out.println("now some timing tests...");

System.out.println();

  

for (long N = 10000; N < 100000; N *= 2)

{

long start = System.nanoTime();

  

addN(N);

  

long end = System.nanoTime();

  

System.out.println("calling add()" + N + " times took " + (end -start) / 1e6 + " ms") }

}

public static SinglyLinkedList<Long> addN(long N)// Auto-generated method stub

{ SinglyLinkedList<Long>slist = new SinglyLinkedList<>();

for (long i = 0; i < N; i++)

{

slist.add(i); }

return slist; }

}

Hope you understand and this helps you.All the best