Question

Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the...

Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the first item containing a given value from a doubly linked list. The header of the method is as follows: public boolean removeValue(T aValue) where T is the general type of the objects in the list and the methods returns true if such an item is found and deleted. Include testing of the method in a main method of the DoublyLList class.

-------------------------------------------------------------------------------------
/**
   A doubly-linked implementation of the ADT list.

   @author Frank M. Carrano
   @author Joseph Erickson
   @version 4.0
 */
public class DoublyLList<T> implements ListInterface<T>
{
        private Node firstNode; // Reference to first node
        private int  numberOfEntries;

        public DoublyLList()
        {
                initializeDataFields();
        } // end default constructor

        public final void clear() // Note the final method
        {
                initializeDataFields();
        } // end clear

        public void add(T newEntry)                             // OutOfMemoryError possible
        {
                Node newNode = new Node(newEntry);

                if (isEmpty())
                        firstNode = newNode;
                else                                                            // Add to end of non-empty list
                {
                        Node lastNode = getNodeAt(numberOfEntries);
                        lastNode.setNextNode(newNode);  // Make last node reference new node
                        newNode.setPreviousNode(lastNode);
                } // end else

                numberOfEntries++;
        }  // end add

        public void add(int newPosition, T newEntry) // OutOfMemoryError possible
        {
                if ((newPosition >= 1) && (newPosition <= numberOfEntries + 1))
                {
                        Node newNode = new Node(newEntry);

                        if (newPosition == 1)                           // Case 1
                        {
                                newNode.setNextNode(firstNode);
                                if (firstNode != null)                          // List is not empty
                                        firstNode.setPreviousNode(newNode);
                                firstNode = newNode;
                        } // end if
                        else                                                            // Case 2: List is not empty
                        {                                                                       // and newPosition > 1
                                Node nodeBefore = getNodeAt(newPosition - 1);
                                Node nodeAfter = nodeBefore.getNextNode();
                                newNode.setNextNode(nodeAfter);
                                newNode.setPreviousNode(nodeBefore);
                                nodeBefore.setNextNode(newNode);
                                if (nodeAfter != null)                  // not the last element
                                        nodeAfter.setPreviousNode(newNode);
                        } // end else

                        numberOfEntries++;
                } // end if
                else
                        throw new IndexOutOfBoundsException("Illegal position given to add operation.");
        } // end add

        public T remove(int givenPosition)
        {
                T result = null;                                                        // Return value

                if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
                {
                        assert !isEmpty();

                        if (givenPosition == 1)                                 // Case 1: Remove first entry
                        {
                                result = firstNode.getData();           // Save entry to be removed
                                firstNode = firstNode.getNextNode();
                                firstNode.setPreviousNode(null);
                        } // end if
                        else                                                                    // Case 2: Not first entry
                        {
                                ///////////////////////////////////////////
                                // INSERT YOUR CODE HERE
                                
                                
                                
                                ///////////////////////////////////////////
                        } // end else

                        numberOfEntries--;
                        return result;
                } // end if
                else
                        throw new IndexOutOfBoundsException("Illegal position given to remove operation.");
        } // end remove

        public T replace(int givenPosition, T newEntry)
        {
                if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
                {   
                        assert !isEmpty();

                        Node desiredNode = getNodeAt(givenPosition);
                        T originalEntry = desiredNode.getData();
                        desiredNode.setData(newEntry);
                        return originalEntry;
                } // end if
                else
                        throw new IndexOutOfBoundsException("Illegal position given to replace operation.");
        } // end replace

        public T getEntry(int givenPosition)
        {
                if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
                {
                        assert !isEmpty();
                        return getNodeAt(givenPosition).getData();
                } // end if
                else
                        throw new IndexOutOfBoundsException("Illegal position given to getEntry operation.");
        } // end getEntry

        public boolean contains(T anEntry)
        {
                boolean found = false;
                Node currentNode = firstNode;

                while (!found && (currentNode != null))
                {
                        if (anEntry.equals(currentNode.getData()))
                                found = true;
                        else
                                currentNode = currentNode.getNextNode();
                } // end while

                return found;
        } // end contains

        public int getLength()
        {
                return numberOfEntries;
        } // end getLength

        public boolean isEmpty()
        {
                boolean result;

                if (numberOfEntries == 0) // Or getLength() == 0
                {
                        assert firstNode == null;
                        result = true;
                } // end if
                else
                {
                        assert firstNode != null;
                        result = false;
                } // end else

                return result;
        } // end isEmpty

        public T[] toArray()
        {
                // The cast is safe because the new array contains null entries
                @SuppressWarnings("unchecked")
                T[] result = (T[])new Object[numberOfEntries];  // Unchecked cast

                int index = 0;
                Node currentNode = firstNode;
                while ((index < numberOfEntries) && (currentNode != null))
                {
                        result[index] = currentNode.getData();
                        currentNode = currentNode.getNextNode();
                        index++;
                } // end while

                        return result;
        } // end toArray

        // Initializes the class's data fields to indicate an empty list.
        private void initializeDataFields()
        {
                firstNode = null;
                numberOfEntries = 0;
        } // end initializeDataFields

        // Returns a reference to the node at a given position.
        // Precondition: List is not empty;
        //               1 <= givenPosition <= numberOfEntries
        private Node getNodeAt(int givenPosition)
        {
                assert !isEmpty() && (1 <= givenPosition) && (givenPosition <= numberOfEntries);
                Node currentNode = firstNode;

                // Traverse the chain to locate the desired node
                // (skipped if givenPosition is 1)
                for (int counter = 1; counter < givenPosition; counter++)
                        currentNode = currentNode.getNextNode();

                assert currentNode != null;

                return currentNode;
        } // end getNodeAt

        private class Node
        {
                private T    data;              // Entry in list
                private Node next;              // Link to next node
                private Node previous;  // Link to previous node

                private Node(T dataPortion)
                {
                        data = dataPortion;
                        next = null;
                        previous = null;
                } // end constructor

                private Node(T dataPortion, Node nextNode)
                {
                        data = dataPortion;
                        next = nextNode;
                        previous = null;
                } // end constructor

                private T getData()
                {
                        return data;
                } // end getData

                private void setData(T newData)
                {
                        data = newData;
                } // end setData

                private Node getNextNode()
                {
                        return next;
                } // end getNextNode

                private void setNextNode(Node nextNode)
                {
                        next = nextNode;
                } // end setNextNode

                private Node getPreviousNode()
                {
                        return previous;
                } // end getPreviousNode

                private void setPreviousNode(Node previousNode)
                {
                        previous = previousNode;
                } // end setPreviousNode
        } // end Node
} // end DoublyLList



-------------------------------------------------------------------------------------------
/** An interface for the ADT list.
    Entries in a list have positions that begin with 1.

    @author Frank M. Carrano
    @author Timothy M. Henry
    @version 4.0
*/
public interface ListInterface<T>
{
   /** Adds a new entry to the end of this list.
       Entries currently in the list are unaffected.
       The list's size is increased by 1.
       @param newEntry  The object to be added as a new entry. */
   public void add(T newEntry);
   
   /** Adds a new entry at a specified position within this list.
       Entries originally at and above the specified position
       are at the next higher position within the list.
       The list's size is increased by 1.
       @param newPosition  An integer that specifies the desired
                           position of the new entry.
       @param newEntry     The object to be added as a new entry.
       @throws  IndexOutOfBoundsException if either
                newPosition < 1 or newPosition > getLength() + 1. */
   public void add(int newPosition, T newEntry);
   
   /** Removes the entry at a given position from this list.
       Entries originally at positions higher than the given
       position are at the next lower position within the list,
       and the list's size is decreased by 1.
       @param givenPosition  An integer that indicates the position of
                             the entry to be removed.
       @return  A reference to the removed entry.
       @throws  IndexOutOfBoundsException if either 
                givenPosition < 1 or givenPosition > getLength(). */
   public T remove(int givenPosition);
   
   /** Removes all entries from this list. */
   public void clear();
   
   /** Replaces the entry at a given position in this list.
       @param givenPosition  An integer that indicates the position of
                             the entry to be replaced.
       @param newEntry  The object that will replace the entry at the
                        position givenPosition.
       @return  The original entry that was replaced.
       @throws  IndexOutOfBoundsException if either
                givenPosition < 1 or givenPosition > getLength(). */
   public T replace(int givenPosition, T newEntry);
   
   /** Retrieves the entry at a given position in this list.
       @param givenPosition  An integer that indicates the position of
                             the desired entry.
       @return  A reference to the indicated entry.
       @throws  IndexOutOfBoundsException if either
                givenPosition < 1 or givenPosition > getLength(). */
   public T getEntry(int givenPosition);
   
   /** Retrieves all entries that are in this list in the order in which
       they occur in the list.
       @return  A newly allocated array of all the entries in the list.
                If the list is empty, the returned array is empty. */
   public T[] toArray();
   
   /** Sees whether this list contains a given entry.
       @param anEntry  The object that is the desired entry.
       @return  True if the list contains anEntry, or false if not. */
   public boolean contains(T anEntry);
   
   /** Gets the length of this list.
       @return  The integer number of entries currently in the list. */
   public int getLength();
       
   /** Sees whether this list is empty.
       @return  True if the list is empty, or false if not. */
   public boolean isEmpty();
} // end ListInterface
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Java Code:

//remove method

public T remove(int givenPosition)
{
T result = null; // Return value
int currentPosition=1;
if ((givenPosition >= 1) && (givenPosition <= numberOfEntries))
{
assert !isEmpty();

if (givenPosition == 1) // Case 1: Remove first entry
{
result = firstNode.getData(); // Save entry to be removed
firstNode = firstNode.getNextNode();
firstNode.setPreviousNode(null);
} // end if
else // Case 2: Not first entry
{
///////////////////////////////////////////
// INSERT YOUR CODE HERE
Node currentNode=firstNode;
while(currentNode!=null){ //iterate through list
if(currentPosition==givenPosition){//if current position matches givenposition
result=currentNode.getData(); // save entry to be removed
Node previousOfCurrent=currentNode.getPreviousNode();//get previous node
Node nextOfCurrent=currentNode.getNextNode(); // get next node

if(previousOfCurrent!=null)
previousOfCurrent.setNextNode(nextOfCurrent); //make previous point to next of //current

else

firstNode=nextOfCurrent;
if(nextOfCurrent!=null)//if next not null make it point to previous of current
nextOfCurrent.setPreviousNode(previousOfCurrent);
  
}
currentPosition++; //iterate to next. increment position
currentNode=currentNode.getNextNode();
}
  
  
///////////////////////////////////////////
} // end else

numberOfEntries--;
return result;
} // end if
else
throw new IndexOutOfBoundsException("Illegal position given to remove operation.");
} // end remove

Add a comment
Know the answer?
Add Answer to:
Problem 3 (List Implementation) (35 points): Write a method in the DoublyLList class that deletes the...
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
  • Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the...

    Java Write an intersection method for the ResizableArrayBag class. The intersection of two bags is the overlapping content of the bags. Intersections are explained in more detail in Chapter 1, #6. An intersecion might contain duplicates. The method should not alter either bag. The current bag and the bag sent in as a parameter should be the same when the method ends. The method header is: public BagInterface<T> intersection(ResizableArrayBag <T> anotherBag) Example: bag1 contains (1, 2, 2, 3) bag2 contains...

  • For the following given class, class Node {   private T    data; // Entry in bag   private...

    For the following given class, class Node {   private T    data; // Entry in bag   private Node next; // Link to next node   private Node()   {    this(null, null);   } // end constructor      private Node(T dataPortion)   {    this(dataPortion, null);   } // end constructor      private Node(T dataPortion, Node nextNode)   {    data = dataPortion;    next = nextNode;   } // end constructor } // end Node which code correctly adds the first entry to an empty bag? A Node newNode = new...

  • Java - data structures Suppose that in the array-based stack, the array doubles in size after...

    Java - data structures Suppose that in the array-based stack, the array doubles in size after multiple push operations. But later on, fewer than half of the array’s locations might actually be used by the stack due to pop operations. Revise the implementation so that its array also can shrink in size as objects are removed from the stack. Accomplishing this task will require two new private methods, as follows: The first new method checks whether we should reduce the...

  • Below is the given code of implementation: #include <string> #include <iostream> #include <list> #include <cassert> using...

    Below is the given code of implementation: #include <string> #include <iostream> #include <list> #include <cassert> using namespace std; class List; class Iterator; class Node { public: /* Constructs a node with a given data value. @param s the data to store in this node */ Node(string s); /* Destructor */ ~Node() {} private: string data; Node* previous; Node* next; friend class List; friend class Iterator; }; class List { public: /** Constructs an empty list. */ List(); /* Destructor. Deletes...

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

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

  • Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements...

    Java help: Please help complete the locate method that is in bold.. public class LinkedDoubleEndedList implements DoubleEndedList { private Node front; // first node in list private Node rear; // last node in list private int size; // number of elements in list ////////////////////////////////////////////////// // YOU MUST IMPLEMENT THE LOCATE METHOD BELOW // ////////////////////////////////////////////////// /** * Returns the position of the node containing the given value, where * the front node is at position zero and the rear node is...

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

  • This Individual Assignment is a set of three problems. The first is a recursion "warm up"...

    This Individual Assignment is a set of three problems. The first is a recursion "warm up" exercise, and the second two are QuickSort variations. The "warm up" should be implemented as a static method in your main App class and the second two will use additional classes (as instructed below). All three problems should be included in the same NetBeans project (exported to ZIP as usual). ----------------- All of your classes should be properly encapsulated, follow all proper coding conventions...

  • I have added a little Code but I need help with the rest. /** A class...

    I have added a little Code but I need help with the rest. /** A class of stacks whose entries are stored in a chain of nodes. Implement all methods in MyStack class Main Reference : text book or class notes Do not change or add data fields */ package PJ2; public class MyStack<T> implements StackInterface<T> {    // Data fields    private Node<T> topNode; // references the first node in the chain    private int numberOfEntries;       public...

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