Question

In: Computer Science

Java The List ADT has an interface and a linked list implementation whose source code is...

Java

The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML:

+hasRepeats() : boolean

hasRepeats() returns true if the list has a value that occurs more than once in the list

hasRepeats() returns false if no value in the list occurs more than once in the list

For example, if a List ADT object is created and has the following values inserted into it:

1, 1, 3, 4, 5

hasRepeats() would return true because the value 1 occurs more than once in the list

but if a List ADT object is created and has the following values inserted into it:

1, 2, 3, 4, 5

hasRepeats() would return false because no value in the list occurs more than once in the list.

The List ADT has methods that may be useful in writing hasRepeats(). You may call any existing methods of the List ADT inside hasRepeats().

Once you have modified the List ADT to have the hasRepeats() method, write a Java Client program that makes a List ADT object, takes integers as input from a user, stores the integers in the List ADT object, and uses the hasRepeats() method to display whether the List ADT object contains repeated values.

The Client program will have a main() method and is the program that is run at the command line. You may give your Client program any name you like. The Client program should perform a loop, ask for input, and display output in the following way.

Input a list of integers: 1 1 3 4 5
The list has repeated values.
Do you want to continue (y/n):  y
  
Input a list of integers: 1 2 10 20 100 200
The list does not have repeated values.
Do you want to continue (y/n):  y
 
Input a list of integers:
The list does not have repeated values.
Do you want to continue (y/n):  y

Input a list of integers: 2
The list does not have repeated values.
Do you want to continue (y/n):  

public interface ListInterface
{
   public void add(T newEntry);
   public void add(int newPosition, T newEntry);
   public T remove(int givenPosition);
   public void clear();
   public T replace(int givenPosition, T newEntry);
   public T getEntry(int givenPosition);
   public T[] toArray();
   public boolean contains(T anEntry);
   public int getLength();
   public boolean isEmpty();
}

public class LList implements ListInterface
{
   private Node firstNode; // reference to the first node of chain
   private int numberOfEntries;
   public LList ()
   {
       initializeDataFields();
   }// end default constructor
  
   public void clear()
   {
       initializeDataFields();
   }//end clear
  
   public void add(T newEntry) // outOfMemoryError possible
   {
       Node newNode = new Node(newEntry);
       if (isEmpty())
           firstNode = newNode;
       else                    // add to end of nonempty link list
       {
           Node lastNode = getNodeAt(numberOfEntries);
           lastNode.setNextNode(newNode);   // Make last node reference new node
          
       }// end if
       numberOfEntries++;
   }// end add
  
   public void add(int givenPosition, T newEntry) // outOfMemoryError possible
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries +1))
       {
           Node newNode = new Node(newEntry);
          
           if(givenPosition == 1)       // case 1
           {
               newNode.setNextNode(firstNode);
               firstNode = newNode;
           }
           else                        // case 2
           {                           // and givenPosition > 1
               Node nodeBefore = getNodeAt(givenPosition -1);
               Node nodeAfter = nodeBefore.getNextNode();
               newNode.setNextNode(nodeAfter);
               nodeBefore.setNextNode(newNode);
           }// end if
           numberOfEntries ++;
       }
       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))
       {   // assertion: !isEmpty
           if(givenPosition == 1)
           {
               result = firstNode.getData();
               firstNode = firstNode.getNextNode();
           }
           else
           {
               Node nodeBefore = getNodeAt(givenPosition -1);
               Node nodeToRemove = nodeBefore.getNextNode();
               result = nodeToRemove.getData();
               Node nodeAfter = nodeToRemove.getNextNode();
               nodeBefore.setNextNode(nodeAfter);
           }
           numberOfEntries--;
           return result;
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to remove operation.");
   }
  
   public T replace(int givenPosition, T newEntry)
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
           Node desiredNode = getNodeAt(givenPosition);
           T originalEntry = desiredNode.getData();
           desiredNode.setData(newEntry);
           return originalEntry;
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to replace operation.");
   }
   public T getEntry(int givenPosition)
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
           return getNodeAt(givenPosition).getData();
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to getEntry operation.");
   }
   public T[] toArray()
   {
       T[] result = (T[])new Object[numberOfEntries];
       int index = 0;
       Node currentNode = firstNode;
       while ((index < numberOfEntries) && (currentNode != null)) {
           result[index] = currentNode.getData();
           currentNode = currentNode.getNextNode();
           index ++;
       }
       return result;
   }
  
  
  
  
   public boolean contain(T anEntry)
   {
       boolean found = false;
       Node currentNode = firstNode;
       while (!found && (currentNode != null)) {
           if (anEntry.equals(currentNode.getData()))
               found = true;
           else
               currentNode = currentNode.getNextNode();
       }
       return found;
   }
   public int getLength() {
       return numberOfEntries;
      
   }
   public boolean isEmpty()
   {
       boolean result;
       if (numberOfEntries == 0) // Or getLength() == 0
       {
           // Assertion: firstNode == null
           result = true;
       }
       else
       {
           // Assertion: firstNode != null
           result = false;
       }
       return result;
   }
   private void initializeDataFields()
   {
       firstNode = null;
       numberOfEntries = 0;
   }
   private Node getNodeAt(int givenPosition)
   {
       Node currentNode = firstNode;
       for (int counter =1; counter < givenPosition; counter++)
           currentNode = currentNode.getNextNode();
       return currentNode;
   }
   private class Node
   {
       private T data;
       private Node next;
      
       private Node(T dataPortion) {
           data = dataPortion;
           next = null;
       }
      
       private Node(T dataPortion, Node nextNode) {
           data = dataPortion;
           next = nextNode;
       }
       private T getData() {
           return data;
       }
       private void setData(T newData) {
           data = newData;
       }
       private Node getNextNode()
       {
           return next;
       }
       private void setNextNode(Node nextNode) {
           next = nextNode;
       }
   }
  
  
}

Solutions

Expert Solution

Java LList Class:

interface ListInterface<T>
{
   public void add(T newEntry);
   public void add(int newPosition, T newEntry);
   public T remove(int givenPosition);
   public void clear();
   public T replace(int givenPosition, T newEntry);
   public T getEntry(int givenPosition);
   public T[] toArray();
   public boolean contains(T anEntry);
   public int getLength();
   public boolean isEmpty();
}

public class LList<T> implements ListInterface<T>
{
   private Node firstNode; // reference to the first node of chain
   private int numberOfEntries;
   public LList ()
   {
       initializeDataFields();
   }// end default constructor
  
   public void clear()
   {
       initializeDataFields();
   }//end clear
  
   public void add(T newEntry) // outOfMemoryError possible
   {
       Node newNode = new Node(newEntry);
       if (isEmpty())
           firstNode = newNode;
       else                    // add to end of nonempty link list
       {
           Node lastNode = getNodeAt(numberOfEntries);
           lastNode.setNextNode(newNode);   // Make last node reference new node
          
       }// end if
       numberOfEntries++;
   }// end add
  
   public void add(int givenPosition, T newEntry) // outOfMemoryError possible
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries +1))
       {
           Node newNode = new Node(newEntry);
          
           if(givenPosition == 1)       // case 1
           {
               newNode.setNextNode(firstNode);
               firstNode = newNode;
           }
           else                        // case 2
           {                           // and givenPosition > 1
               Node nodeBefore = getNodeAt(givenPosition -1);
               Node nodeAfter = nodeBefore.getNextNode();
               newNode.setNextNode(nodeAfter);
               nodeBefore.setNextNode(newNode);
           }// end if
           numberOfEntries ++;
       }
       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))
       {   // assertion: !isEmpty
           if(givenPosition == 1)
           {
               result = firstNode.getData();
               firstNode = firstNode.getNextNode();
           }
           else
           {
               Node nodeBefore = getNodeAt(givenPosition -1);
               Node nodeToRemove = nodeBefore.getNextNode();
               result = nodeToRemove.getData();
               Node nodeAfter = nodeToRemove.getNextNode();
               nodeBefore.setNextNode(nodeAfter);
           }
           numberOfEntries--;
           return result;
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to remove operation.");
   }
  
   public T replace(int givenPosition, T newEntry)
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
           Node desiredNode = getNodeAt(givenPosition);
           T originalEntry = desiredNode.getData();
           desiredNode.setData(newEntry);
           return originalEntry;
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to replace operation.");
   }
   public T getEntry(int givenPosition)
   {
       if ((givenPosition >= 1) && (givenPosition <= numberOfEntries)) {
           return getNodeAt(givenPosition).getData();
       }
       else
           throw new IndexOutOfBoundsException("illegal position given to getEntry operation.");
   }
   public T[] toArray()
   {
       T[] result = (T[])new Object[numberOfEntries];
       int index = 0;
       Node currentNode = firstNode;
       while ((index < numberOfEntries) && (currentNode != null)) {
           result[index] = currentNode.getData();
           currentNode = currentNode.getNextNode();
           index ++;
       }
       return result;
   }
   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();
       }
       return found;
   }
   public int getLength() {
       return numberOfEntries;
      
   }
   public boolean isEmpty()
   {
       boolean result;
       if (numberOfEntries == 0) // Or getLength() == 0
       {
           // Assertion: firstNode == null
           result = true;
       }
       else
       {
           // Assertion: firstNode != null
           result = false;
       }
       return result;
   }
   private void initializeDataFields()
   {
       firstNode = null;
       numberOfEntries = 0;
   }
   private Node getNodeAt(int givenPosition)
   {
       Node currentNode = firstNode;
       for (int counter =1; counter < givenPosition; counter++)
           currentNode = currentNode.getNextNode();
       return currentNode;
   }
   private class Node
   {
       private T data;
       private Node next;
      
       private Node(T dataPortion) {
           data = dataPortion;
           next = null;
       }
      
       private Node(T dataPortion, Node nextNode) {
           data = dataPortion;
           next = nextNode;
       }
       private T getData() {
           return data;
       }
       private void setData(T newData) {
           data = newData;
       }
       private Node getNextNode()
       {
           return next;
       }
       private void setNextNode(Node nextNode) {
           next = nextNode;
       }
   }

   public boolean hasRepeats()
   {
     for(int i=1;i<numberOfEntries;i++)
     {
       T data=getEntry(i);
       for(int j=i+1;j<numberOfEntries+1;j++)
       {
         if(data==getEntry(j))
         {
           return true;
         }
       }
     }
     return false;
   }
}

Java Client Program:

import java.io.*; 
import java.util.Scanner; 

class Main {
  public static void main(String[] args) {
    Scanner sc = new Scanner(System.in); 
    while(true)
    {
      System.out.print("Input a list of integers:");
      LList l=new LList();
      String ar[]=sc.nextLine().split(" ");
      for(int i=0;i<ar.length;i++)
      {
        l.add(Integer.parseInt(ar[i]));
      }
      if(l.hasRepeats())
      {
        System.out.println("The list has repeated values.");
      }
      else
      {
        System.out.println("The list does not have repeated values.");
      }
      System.out.print("Do you want to continue (y/n):");
      String c=sc.nextLine();
      System.out.println();
      if(c.equals("n"))
      {
        break;
      }
    }
  }
}

Sample Output:


Related Solutions

Java The List ADT has an interface and a linked list implementation whose source code is...
Java The List ADT has an interface and a linked list implementation whose source code is given at the bottom of this programming lab description. You are to modify the List ADT's source code by adding the method corresponding to the following UML: +hasRepeats() : boolean hasRepeats() returns true if the list has a value that occurs more than once in the list hasRepeats() returns false if no value in the list occurs more than once in the list For...
In C++, Implement the queue ADT with a singly linked list
In C++, Implement the queue ADT with a singly linked list
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added....
Add a copy constructor for the linked list implementation below. Upload list.cpp with your code added. (DO NOT MODIFY THE HEADER FILE OR TEST FILE. only modify the list.cpp) /*LIST.CPP : */ #include "list.h" using namespace std; // Node class implemenation template <typename T> Node<T>::Node(T element) { // Constructor    data = element;    previous = nullptr;    next = nullptr; } // List implementation template <typename T> List<T>::List() {    head = nullptr;    tail = nullptr; } template...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in...
Array-Based Linked List Implementation: JAVA Decide how to write the methods with items being stored in an array. NOT in linked List. Implement an array-based Linked List in your language. Use double as the item. You need to create a driver includes several items and inserts them in order in a list. Identify the necessary methods in a List Linked implementation. Look at previous Data Structures (stack or queue) and be sure to include all necessary methods. DO NOT USE...
Java OVERVIEW This program primarily focuses on the implementation of a ArrayList type interface and the...
Java OVERVIEW This program primarily focuses on the implementation of a ArrayList type interface and the necessary methods to implement the ArrayList. It also includes polymorphism and class comparison. INSTRUCTIONS Your deliverable will be to turn in three files. The files will be named Card.java, PremiumCard.java and the last file will be called CardArrayList.java. For this assignment, any use of a data control structure other than a simple Arrary or String will result in no credit. I am aware that...
Please write in JAVA 1. Given the following array-based ADT list called colorList whose elements contain...
Please write in JAVA 1. Given the following array-based ADT list called colorList whose elements contain strings             red, orange, yellow, blue, indigo, violet write the statement to insert the String element “pink” to the end of the list. Assume the front of the list is on the left. 2. Outline the basic steps to remove a node from the beginning of a list. Completed answers will be given an immediate upvote :)
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector...
In C++ write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items.
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class...
Question: Write an implementation of the ADT sorted list that uses a resizable array (vector class of C++ STL) to represent the list items. Anytime the list becomes full, double the size of the array.
Create a generic Linked List that does NOT use the Java library linked list. Make sure...
Create a generic Linked List that does NOT use the Java library linked list. Make sure it contains or access a subclass named Node (also Generic). And has the methods: addFirst(), addLast(), add(), removeFirst(), removeLast() and getHead(). In a separate Java class provide a main that creates an instance of your LinkedList class that creates an instance of your LinkedList that contains String types. Add the five names (you pick them) to the list and then iterate through the list...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and...
Data Structures on Java Basic Linked List exercises a. Suppose x is a linked-list node and not the last node on the list. What is the effect of the following code fragment? x.next = x.next.next b. Singly Linked List has two private instance variables first and last as that point to the first and the last nodes in the list, respectively. Write a fragment of code that removes the last node in a linked list whose first node is first....
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT