Question

In the first exercise, you will override the add method in a subclass in order to...

In the first exercise, you will override the add method in a subclass in order to improve its performance. In the second exercise, you will implement an Iterator for your new linked list class.

Exercise 1

The add method of the linked list class discussed during lecture performs in O(N) time. What can be done to improve its performance to O(1)? What are the boundary cases? Define a new class that inherits from the CS20bLinkedList class introduced during the lecture. Override the add method and implement it to perform in O(1) and be sure that it works for all boundary cases.

Note: You are not required to override (update) any of the other methods of the linked list class.

Exercise 2

Based on your new linked list subclass, create a new iterator class that iterates over the values stored in that linked list. You will need to use the following two interfaces as discussed during lecture:

• java.lang.Iterable<T>:TheIterableinterfacemustbeimplementedbyyournew subclass which implements the iterator() method. This will define the class as a collection on which an iterator can be used to traverse the elements.

• java.util.Iterator<T>:TheIteratorinterfacemustbeimplementedbyanewclass which defines how the linked list is traversed by implementing the hasNext() and next()methods.

The inner Node class and the head instance variable must not have an access modifier (previously declared private).

package list;

/**

* A linked list class

* @author N. Kalisch

*/

public class CS20bLinkedList {

/**

* Represents a node in the linked list

*/

class Node {

int value;// value stored in this node

Node next;// reference to next node

/**

* Constructor

*/

Node(int val) {

this.value = val;

}

/**

* Checks if next node exists

* @return true if next node exists

*/

boolean hasNext() {

return next != null;

}

}

// The reference to the very first node of the class, initially null

Node head;

/**

* Adds a new value to the end of the list

* @param value that will be added

*/

public void add(int value) {

if (head == null) {

head = new Node(value);

return;

}

Node tmp = head;

while (tmp.hasNext()) {

tmp = tmp.next;

}

tmp.next = new Node(value);

}

/**

* Checks if the given target value exists in this list

* @param target to be searched

* @return true if target exists

*/

public boolean contains(int target) {

if (head == null) {

return false;

}

Node tmp = head;

while (tmp != null) {

if (tmp.value == target) {

return true;

}

tmp = tmp.next;

}

return false;

}

/**

* Removes the given target from this list

* @param target to be removed

* @return true if target was found and removed

*/

public boolean remove(int target) {

if (head == null) {

return false;

}

if (head.value == target) {

head = head.next;

return true;

}

Node tmp = head;

while (tmp.hasNext()) {

if (tmp.next.value == target) {

tmp.next = tmp.next.next;

return true;

}

tmp = tmp.next;

}

return false;

}

}

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

import java.util.Iterator;

public class CS20bLinkedList implements Iterable<Integer>{

       /**

       * Represents a node in the linked list

       */

       class Node {

       int value;// value stored in this node

       Node next;// reference to next node

       /**

       * Constructor

       */

       Node(int val) {

       this.value = val;

       }

       /**

       * Checks if next node exists

       * @return true if next node exists

       */

       boolean hasNext() {

       return next != null;

       }

       }

       // The reference to the very first node of the class, initially null

       Node head;

       Node tail; // add a node to point to end of the list

       /**

       * Adds a new value to the end of the list

       * @param value that will be added

       // performs addition of node in O(1)

       */

       public void add(int value) {

             if (head == null)

             {

                    head = new Node(value);

                    tail = head;

                    return;

      

             }else {

                    Node node = new Node(value);

                    tail.next = node;

                    tail = node;

             }

            

       }

       /**

       * Checks if the given target value exists in this list

       * @param target to be searched

       * @return true if target exists

       */

       public boolean contains(int target) {

       if (head == null) {

       return false;

       }

       Node tmp = head;

       while (tmp != null) {

       if (tmp.value == target) {

       return true;

       }

       tmp = tmp.next;

       }

       return false;

       }

       /**

       * Removes the given target from this list

       * @param target to be removed

       * @return true if target was found and removed

       */

       public boolean remove(int target) {

       if (head == null) {

       return false;

       }

       if (head.value == target) {

             head = head.next;

             if(head == null)

                    tail = null;

             return true;

       }

       Node tmp = head;

       while (tmp.hasNext()) {

       if (tmp.next.value == target) {

             tmp.next = tmp.next.next;

             if(tmp.next == null)

                    tail = tmp;

       return true;

       }

       tmp = tmp.next;

       }

       return false;

       }

      

       // iterator class for linked list

       class CS20bLinkedListIterator implements Iterator<Integer>

       {

            

             Node curr;

             public CS20bLinkedListIterator(CS20bLinkedList list)

             {

                    curr = list.head;

             }

             @Override

             public boolean hasNext() {

                    return(curr != null);

                   

             }

             @Override

             public Integer next() {

                   

                    int data = curr.value;

                    curr = curr.next;

                    return data;

             }

            

       }

      

       @Override

       public Iterator<Integer> iterator() {

             return new CS20bLinkedListIterator(this);

       }

}

Add a comment
Know the answer?
Add Answer to:
In the first exercise, you will override the add method in a subclass in order to...
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
  • In Java You may add any classes or methods to the following as you see fit in order to complete t...

    In Java You may add any classes or methods to the following as you see fit in order to complete the given tasks. Modify the LinkedList (or DoubleLinkedList) class and add a method append. append should take another LinkedList (DoubleLinkedList) as input and append that list to the end of this list. The append method should work by doing a few "arrow" adjustments on the boxes and it should not loop through the input list to add elements one at...

  • Given a singly-linked list interface and linked list node class, implement the singly-linked list which has...

    Given a singly-linked list interface and linked list node class, implement the singly-linked list which has the following methods in Java: 1. Implement 3 add() methods. One will add to the front (must be O(1)), one will add to the back (must be O(1)), and one will add anywhere in the list according to given index (must be O(1) for index 0 and O(n) for all other indices). They are: void addAtIndex(int index, T data), void addToFront(T data), void addToBack(T...

  • Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to...

    Please use Java programming: Modify both ArrayList and LinkedList classes and add the following method to both classes: public void reverseThisList(), This method will reverse the lists. When testing the method: print out the original list, call the new method, then print out the list again ------------------------------------------------------------------------- //ARRAY LIST class: public class ArrayList<E> implements List<E> { /** Array of elements in this List. */ private E[] data; /** Number of elements currently in this List. */ private int size; /**...

  • In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying...

    In Java Language. Modify the LinkedPostionalList class to support a method swap(p,q) that causes the underlying nodes referenced by positions p and q to be exchanged for each other. Relink the existing nodes, do not create any new nodes. ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- package lists; import java.util.Iterator; import java.util.NoSuchElementException; public class LinkedPositionalList implements PositionalList { //---------------- nested Node class ---------------- /** * Node of a doubly linked list, which stores a reference to its * element and to both the previous and next...

  • Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test...

    Complete P16.1 and P16.4 (Class Name: NewMethodDemo) Once complete, upload all .java files. For primary test class: Remember your header with name, date, and assignment. Also include class names that will be tested. Psuedocode (level 0 or mixture of level 0 and algorithm [do not number steps]) is required if main() contains more than simple statements (for example, your program includes constructs for decisions (if/else), loops, and methods. For Secondary class(es): Include a JavaDoc comment that describes the purpose of...

  • 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...

  • 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;...

  • In java Write a method public void printReverse() that prints the elements of a doubly linked...

    In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...

  • In java Write a method public void printReverse() that prints the elements of a doubly linked...

    In java Write a method public void printReverse() that prints the elements of a doubly linked list in reverse. Write a method public void delete5FromTheEnd() which deletes the 5th element from end of the list. Note that if you reach the end then you have to reverse the direction of counting. In the main() method of the test class, create a randomly generated Doubly-Linked list of 10 Integers. Next, call the delete5FromTheEnd() method and print the lists iteratively until the...

  • In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {...

    In Java. How would this method look? LinkedBinaryTree.java import java.util.Iterator; public class LinkedBinaryTree implements BinaryTreeADT {    private BinaryTreeNode root;    /**    * Creates an empty binary tree.    */    public LinkedBinaryTree() {        root = null;    }    /**    * Creates a binary tree from an existing root.    */    public LinkedBinaryTree(BinaryTreeNode root) {        this.root = root;    }    /**    * Creates a binary tree with the specified element...

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
ADVERTISEMENT