Question

Improve the speed of public T get(int i) by having it work backward from the end...

Improve the speed of public T get(int i) by having it work backward from the end of the array if you attempt to get a member which is closer to the end than the start. This improvement will be tested through timing tests on large lists. The method should still return null if i is not a valid index.

Code

import java.util.Iterator;

public class DLList<T> implements Iterable<T> {
   private static class Node<T> {
       public Node<T> prev, next;
       public T data;

       public Node(Node<T> prev, T data, Node<T> next) {
           this.prev = prev;
           this.next = next;
           this.data = data;

       }
   }

   private int numNodes;
   private Node<T> head, tail;

   private static class Conductor<T> implements Iterator<T> {
       public Node<T> car;

       public Conductor(DLList<T> list) {
           car = list.head;

       }

       public boolean hasNext() {
           return car != null;
       }

       public T next() {
           T data = car.data;
           car = car.next;
           return data;

       }

       public void remove() {
       }
   }

   public DLList() {
       head = tail = null;
   }

   public void add(T data) {
       if (tail == null) {
           head = new Node<T>(null, data, null);
           tail = head;
       } else {
           tail.next = new Node<T>(tail, data, null);
           tail = tail.next;
       }
       numNodes++;
   }

   public int size() {
       return numNodes;
   }

   public T get(int i) {
       if (i < 0)
           throw new IndexOutOfBoundsException();
       Node<T> current = head;
       for (int j = 0; current != null && j < i; j++) {
           current = current.next;
       }
       if (current == null)
           throw new IndexOutOfBoundsException();
       return current.data;
   }

   public T remove(int i) {
       if (i < 0)
           throw new IndexOutOfBoundsException();
       Node<T> current = head;
       for (int j = 0; current != null && j < i; j++) {
           current = current.next;
       }
       if (current == null)
           throw new IndexOutOfBoundsException();
       if (current.prev != null)
           current.prev.next = current.next;
       else
           head = head.next;
       if (current.next != null)
           current.next.prev = current.prev;
       else
           tail = tail.prev;
       numNodes--;
       return current.data;
   }

   public Iterator<T> iterator() {
       return new Conductor<T>(this);
   }

   private static class BackwardConductor<T> implements Iterator<T> {
       public Node<T> car;

       public BackwardConductor(DLList<T> list) {
           car = list.tail;
       }

       public boolean hasNext() {
           return car != null;
       }

       public T next() {
           T data = car.data;
           car = car.prev;
           return data;
       }

       public void remove() {
       }
   }

   public Iterator<T> descendingIterator() {
       return new BackwardConductor<T>(this);

   }

   public void reverse() {
       Node<T> temp = head, temp2;
       if (temp != null) {
           head = tail;
           tail = temp;
           temp = head;
           while (temp != tail) {
               temp2 = temp.next;
               temp.next = temp.prev;
               temp.prev = temp2;
               temp = temp.next;
           }
           temp2 = temp.next;
           temp.next = temp.prev;
           temp.prev = temp2;
       }
   }

   public boolean add(int i, T s) {
       if (i < 0 || i >= size()) {
           return false;
       }
       Node temp = head;
       for (int index = 0; index < i; index++) {
           temp = temp.next;
       }
       Node newNode = new Node<T>(temp.prev, s, temp);
       if (temp == head) {
           head.prev = newNode;
           head = newNode;
           numNodes++;
           return true;
       }
       temp.prev.next = newNode;
       temp.prev = newNode;
       numNodes++;
       return true;
   }

}

0 0
Add a comment Improve this question Transcribed image text
Answer #1

public T get(int i)
{
   int n = size();//getting size of the list
   if(0<=i && i<n)//if valid index
   {
       int s=i+1;
       int e = n-s;
       if(s<e)//then it is closer to starting
       {
           Node<T> temp = head;
           s=s-1;
           while(temp!=null && 0<s)
           {
               temp=temp.next;
               s--;  
           }
           return temp.data;//return element at index i
       }
       else//then it is closer to ending
       {
           Node<T> temp =tail;
           s=e;
           while(temp!=null && 0<s)
           {
               temp=temp.prev;
               s--;  
           }
           return temp.data;//return element at index i
          
       }
      
   }
  
   return null;//if not valid index
  
}

Add a comment
Know the answer?
Add Answer to:
Improve the speed of public T get(int i) by having it work backward from the end...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • I need help with todo line please public class LinkedList { private Node head; public LinkedList()...

    I need help with todo line please public class LinkedList { private Node head; public LinkedList() { head = null; } public boolean isEmpty() { return head == null; } public int size() { int count = 0; Node current = head; while (current != null) { count++; current = current.getNext(); } return count; } public void add(int data) { Node newNode = new Node(data); newNode.setNext(head); head = newNode; } public void append(int data) { Node newNode = new Node(data);...

  • Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: ...

    Hi! Can someone can convert this java code to c++. ASAP thanks I will thumbs up Here's the code: package lists; import bookdata.*; public class DoublyLinkedList { int size; //Variable que define el tamano de la lista. Node head, tail; //Nodos que definen el Head y Tail en la lista. //Constructor public DoublyLinkedList(){ this.head = null; this.tail = null; this.size = 0; } //Insert a new book in alphabetic order. public void insert(Book nb){ //Creamos uno nuevo nodo con el...

  • Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)...

    Java Programming: The following is my code: public class KWSingleLinkedList<E> {    public void setSize(int size)    {        this.size = size;    }    /** Reference to list head. */    private Node<E> head = null;    /** The number of items in the list */    private int size = 0;       /** Add an item to the front of the list.    @param item The item to be added    */    public void addFirst(E...

  • Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k...

    Add the following method to xxxxxp3: // deletes x from sorted list k if exist, k = 0, 1, 2 private void delete(x, k) // returns position of x in sorted list k if exist otherwise, -1. k = 0, 1, 2 private int search(x, k) import java.util.Scanner; class xxxxxp3{ private node[] head = new node[3]; private class node{ int num; node link; node(int x){ num=x; link = null; } } public void prtlst(int k){ System.out.printf("\nContents of List-%d:",k); for(node cur...

  • I have a Java Data Structures project and we're creating a linked list and an iterator...

    I have a Java Data Structures project and we're creating a linked list and an iterator for that linked list. The add method for the linked list has to be O(1). This is my code public class MyLinkedList extends CS20bLinkedList implements Iterable<Integer> {        @Override      public void add(int value){                        Node tail = head;            if(head == null){                        head = new Node(value);             //System.out.println("Very Fun! "+head.value);                        return;                }else{           ...

  • JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has...

    JAVA: Already completed: MyList.java, MyAbstractList.java, MyArrayList.java, MyLinkedLink.java, MyStack.java, MyQueue.java. Need to complete: ReversePoem.java. This program has you display a pessimistic poem from a list of phrases. Next, this program has you reverse the phrases to find another more optimistic poem. Use the following algorithm. 1.   You are given a list of phrases each ending with a pound sign: ‘#’. 2.   Create a single String object from this list. 3.   Then, split the String of phrases into an array of phrases...

  • Currently working on a Java Assignment. I have written most codes for swap, reverse and insert....

    Currently working on a Java Assignment. I have written most codes for swap, reverse and insert. Just need a. itemCount receives a value and returns a count of the number of times this item is found in the list. c. sublist receives two indexes and returns an ArrayList of node values from the first index to the second index, provided the indexes are valid. d. select receives a variable number of indexes, and returns an ArrayList of node values corresponding...

  • When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses...

    When compiling the LinkedList and Iterator class, the following error is being produced: Note: LinkedList.java uses unchecked or unsafe operations. Note: Recompile with -Xlint:unchecked for details. Any suggestions? public class LinkedList<T> {    Node<T> itsFirstNode;    Node<T> itsLastNode;    private int size;    public LinkedList() {        itsFirstNode = null;        itsLastNode = null;          size = 0;    }    public Iterator<T> getIterator() {        return new Iterator(this);    }    // THIS WILL NEED...

  • (1) Implement the countKey(T element) method, which should return a count of the number of times...

    (1) Implement the countKey(T element) method, which should return a count of the number of times that the given key (the element) is found in the list. (2) Implement the indexOf(T element) method, which is similar as the indexOf method in the String class. It returns the index (the position starting from the head node) of the first occurrence of the given element, or -1, if the element does not occur in the list. You will need to track the...

  • Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(),...

    Problem 2: based on java.util.LinkedList class, create MyStack class that should have the methods: push(), pop(), peek(), size(), isEmpty(). my linkedlist class is: public class Lab8_problem1 {    private Node head, tail; private int size;    public Lab8_problem1() { this.head = null; this.tail = null; this.size = 0; } //Insert a node at specifc Location public void insertAt(int value, int index) { Node newNode = new Node(); newNode.data = value; if(head == null){ head = newNode; tail = newNode; head.next...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT