Question

(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 index as you traverse the linked list.

(3) Implement the printList() method simply prints the contents of the list to the terminal. For example, if the list is empty, it should print [ ], and if the list contains the elements 1, 2, 3, then it should print [1 -> 2 -> 3].

4) Implement the moveLastToFirst() method, which moves the last element to the front of the list. For example, if the list is 1->2->3->4, then the method should change the list to 4->1->2->3. There is a tail attribute in the given LinkedList class which point to the last node in the list. Don’t forget to change the previous node of the tail node as the new tail node.

Java Code:

LinkedList.java

package lab1;
/**
* LinkedList represents a linked implementation of a list.

public class LinkedList<T>
{
protected int count;
protected LinearNode<T> head, tail;
  
/**
* Creates an empty list.
*/
public LinkedList()
{
count = 0;
head = tail = null;
   }

/**
* Add the element to the front in this list
*
* @param elem the element that needs to be added to the front in the list
*/
public void addToFirst(T elem) {
   LinearNode<T> newNode = new LinearNode<T>(elem);
  
   if(isEmpty()) {
       head = newNode;
       tail = newNode;
   }
   else {
       newNode.setNext(head);
       head = newNode;
       newNode = null;
   }
   count++;      
}
  
/**
* Add the element to the back in this list
*
* @param elem the element that needs to be added to the back in the list
*/
public void addToLast(T elem) {
   LinearNode<T> newNode = new LinearNode<T>(elem);
  
   if(isEmpty()) {
       head = newNode;
       tail = newNode;
   }
   else {
       tail.setNext(newNode);
       tail = newNode;
       newNode = null;
   }
   count++;
}
  
  
/**
* Removes the first element in this list and returns a reference
* to it. Throws an EmptyCollectionException if the list is empty.
*
* @return a reference to the first element of this list
* @throws EmptyCollectionException if the list is empty
*/
public T removeFirst() throws EmptyCollectionException
{
       if (isEmpty())
throw new EmptyCollectionException("LinkedList");
      
       T result = head.getElement();
       head = head.getNext();
       count--;
      
       return result;
}

/**
* Removes the last element in this list and returns a reference
* to it. Throws an EmptyCollectionException if the list is empty.
*
* @return the last element in this list
* @throws EmptyCollectionException if the list is empty
*/
public T removeLast() throws EmptyCollectionException
{
       if (isEmpty())
throw new EmptyCollectionException("LinkedList");

       T result = tail.getElement();
      
       LinearNode<T> current = head;
       while(current.getNext() != tail)
           current = current.getNext();
      
       current.setNext(null);
       tail = current;
      
       count--;
      
       return result;
}
  
/**
* Returns the first element in this list without removing it.
*
* @return the first element in this list
   * @throws EmptyCollectionException if the list is empty
*/
public T first() throws EmptyCollectionException
{
       if (isEmpty())
throw new EmptyCollectionException("LinkedList");
      
return head.getElement();
}
  
/**
* Returns the last element in this list without removing it.
*
* @return the last element in this list
   * @throws EmptyCollectionException if the list is empty
*/
public T last() throws EmptyCollectionException
{
       if (isEmpty())
throw new EmptyCollectionException("LinkedList");
      
return tail.getElement();
}

  
public LinearNode<T> findFirstKey(T element){
  
   if (isEmpty())
throw new EmptyCollectionException("LinkedList");
  
   LinearNode<T> current = head;
  
   while(current != null && current.getElement() != element) {
       current = current.getNext();
   }
  
   return current;
}
  
public void deleteNode(T element) {
   if (isEmpty())
throw new EmptyCollectionException("LinkedList");
  
   LinearNode<T> current = head, prev = null;
  
   // If head node holds the key to be deleted
   if(current != null && current.getElement() == element) {
       head = current.getNext();
       current.setNext(null);
       return;
   }
  
   //Search for the key to be deleted, track the previous node
   while(current != null && current.getElement() != element) {
       prev = current;
       current = current.getNext();
   }
  
   //If key was not present in the list
   if(current == null)
       return;
  
   prev.setNext(current.getNext());
   current.setNext(null);   
}
  
/**
* Returns true if this list is empty and false otherwise.
*
* @return true if the list is empty, false otherwise
*/
public boolean isEmpty()
{
return (count == 0);
}

/**
* Returns the number of elements in this list.
*
* @return the number of elements in the list
*/
public int size()
{
return count;
}

/**
* Returns a string representation of this list.
*
* @return a string representation of the list
*/
public String toString()
{
LinearNode<T> current = head;
String result = "";

while (current != null)
{
result = result + current.getElement() + "\n";
current = current.getNext();
}

return result;
}
  
  
/*Question 1*/
  
public int countKey(T element) {
   if (isEmpty())
throw new EmptyCollectionException("LinkedList is empty");

   int counter = 0;
  
   /* write your code here */
  
  
   return counter;
  
}
  
/* Question 2 */
public int indexOf(T element) {
   if (isEmpty())
throw new EmptyCollectionException("LinkedList is empty");
  
   /* write your code here */
  
  
   return -1;
}
  
/* Question 3 */
public void printList() {   
  
   /* write your code here*/
  
}
  
/* Question 4 */
public void movelastToFirst() {
   if (isEmpty())
throw new EmptyCollectionException("LinkedList is empty");

   /* write your code here*/
  

}
  
  
}

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

Here is the completed code for this problem. Comments are included, go through it, learn how things work and let me know if you have any doubts or if you need anything to change. If you are satisfied with the solution, please rate the answer. Thanks

// LinkedList.java

package lab1;

public class LinkedList<T> {

    protected int count;

    protected LinearNode<T> head, tail;

    /**

    * Creates an empty list.

    */

    public LinkedList() {

         count = 0;

         head = tail = null;

    }

    /**

    * Add the element to the front in this list

    *

    * @param elem

    *            the element that needs to be added to the front in the list

    */

    public void addToFirst(T elem) {

         LinearNode<T> newNode = new LinearNode<T>(elem);

         if (isEmpty()) {

             head = newNode;

             tail = newNode;

         } else {

             newNode.setNext(head);

             head = newNode;

             newNode = null;

         }

         count++;

    }

    /**

    * Add the element to the back in this list

    *

    * @param elem

    *            the element that needs to be added to the back in the list

    */

    public void addToLast(T elem) {

         LinearNode<T> newNode = new LinearNode<T>(elem);

         if (isEmpty()) {

             head = newNode;

             tail = newNode;

         } else {

             tail.setNext(newNode);

             tail = newNode;

             newNode = null;

         }

         count++;

    }

    /**

    * Removes the first element in this list and returns a reference to it.

    * Throws an EmptyCollectionException if the list is empty.

    *

    * @return a reference to the first element of this list

    * @throws EmptyCollectionException

    *             if the list is empty

    */

    public T removeFirst() throws EmptyCollectionException {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         T result = head.getElement();

         head = head.getNext();

         count--;

         return result;

    }

    /**

    * Removes the last element in this list and returns a reference to it.

    * Throws an EmptyCollectionException if the list is empty.

    *

    * @return the last element in this list

    * @throws EmptyCollectionException

    *             if the list is empty

    */

    public T removeLast() throws EmptyCollectionException {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         T result = tail.getElement();

         LinearNode<T> current = head;

         while (current.getNext() != tail)

             current = current.getNext();

         current.setNext(null);

         tail = current;

         count--;

         return result;

    }

    /**

    * Returns the first element in this list without removing it.

    *

    * @return the first element in this list

    * @throws EmptyCollectionException

    *             if the list is empty

    */

    public T first() throws EmptyCollectionException {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         return head.getElement();

    }

    /**

    * Returns the last element in this list without removing it.

    *

    * @return the last element in this list

    * @throws EmptyCollectionException

    *             if the list is empty

    */

    public T last() throws EmptyCollectionException {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         return tail.getElement();

    }

    public LinearNode<T> findFirstKey(T element) {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         LinearNode<T> current = head;

         while (current != null && current.getElement() != element) {

             current = current.getNext();

         }

         return current;

    }

    public void deleteNode(T element) {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList");

         LinearNode<T> current = head, prev = null;

         // If head node holds the key to be deleted

         if (current != null && current.getElement() == element) {

             head = current.getNext();

             current.setNext(null);

             return;

         }

         // Search for the key to be deleted, track the previous node

         while (current != null && current.getElement() != element) {

             prev = current;

             current = current.getNext();

         }

         // If key was not present in the list

         if (current == null)

             return;

         prev.setNext(current.getNext());

         current.setNext(null);

    }

    /**

    * Returns true if this list is empty and false otherwise.

    *

    * @return true if the list is empty, false otherwise

    */

    public boolean isEmpty() {

         return (count == 0);

    }

    /**

    * Returns the number of elements in this list.

    *

    * @return the number of elements in the list

    */

    public int size() {

         return count;

    }

    /**

    * Returns a string representation of this list.

    *

    * @return a string representation of the list

    */

    public String toString() {

         LinearNode<T> current = head;

         String result = "";

         while (current != null) {

             result = result + current.getElement() + "\n";

             current = current.getNext();

         }

         return result;

    }

    /* Question 1 */

    public int countKey(T element) {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList is empty");

         int counter = 0;

         // using a for loop, looping through each node

         for (LinearNode<T> node = head; node != null; node = node.getNext()) {

             // incrementing counter if node's element is target element

             if (node.getElement().equals(element)) {

                 counter++;

             }

         }

         return counter;

    }

    /* Question 2 */

    public int indexOf(T element) {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList is empty");

         // initializing index to 0

         int index = 0;

         // using a for loop, looping through each node

         for (LinearNode<T> node = head; node != null; node = node.getNext()) {

             // if current node's element equals target, returning index, else

             // incrementing index

             if (node.getElement().equals(element)) {

                 return index;

             }

             index++;

         }

         return -1; // not found

    }

    /* Question 3 */

    public void printList() {

         // printing [ ] if list is empty

         if (isEmpty()) {

             System.out.println("[ ]");

         } else {

             // printing a '['

             System.out.print("[");

             // looping and printing data of each node

             for (LinearNode<T> node = head; node != null; node = node.getNext()) {

                 System.out.print(node.getElement());

                 // if this is not last node, printing " -> "

                 if (node != tail) {

                      System.out.print(" -> ");

                 }

             }

             // finishing with ']'

             System.out.println("]");

         }

    }

    /* Question 4 */

    public void movelastToFirst() {

         if (isEmpty())

             throw new EmptyCollectionException("LinkedList is empty");

         // fetching data of tail node

         T last = tail.getElement();

         // removing tail node

         removeLast();

         // adding removed value to the front

         addToFirst(last);

    }

}

Add a comment
Know the answer?
Add Answer to:
(1) Implement the countKey(T element) method, which should return a count of the number of times...
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
  • There is a data structure called a drop-out stack that behaves like a stack in every...

    There is a data structure called a drop-out stack that behaves like a stack in every respect except that if the stack size is n, then when the n+1element is pushed, the bottom element is lost. Implement a drop-out stack using links, by modifying the LinkedStack code. (size, n, is provided by the constructor. Request: Please create a separate driver class, in a different file, that tests on different types of entries and show result of the tests done on...

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

  • In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These...

    In addition to the base files, three additional files are attached: EmptyCollectionException.java, LinearNode.java, and StackADT.java. These files will need to be added to your Java project. They provide data structure functionality that you will build over. It is suggested that you test if these files have been properly added to your project by confirming that Base_A05Q1.java compiles correctly. Complete the implementation of the ArrayStack class. Specifically, complete the implementations of the isEmpty, size, and toString methods. See Base_A05Q1.java for a...

  • ------------------------------------------------------------------------------------------------------------ CODE ALREADY HAVE BELOW--------------------------------------------------------------------------------------- public class LinkedQueue<T>

    ------------------------------------------------------------------------------------------------------------ CODE ALREADY HAVE BELOW--------------------------------------------------------------------------------------- public class LinkedQueue<T> implements QueueADT<T> {    private int count;    private LinearNode<T> head;    private LinearNode<T> tail;               public LinkedQueue()    {        count = 0;        head = null;        tail = null;    }    @Override    public void enqueue(T element)    {        LinearNode<T> node = new LinearNode<T> (element);        if(isEmpty())            head = node;        else           ...

  • Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of...

    Complete the implementation of the LinkedStack class presented in Chapter 13. Specifically, complete the implementations of the peek, isEmpty, size, and toString methods. See Base_A06Q1.java for a starting place and a description of these methods. Here is the base given: /** * Write a description of the program here. * * @author Lewis et al., (your name) * @version (program version) */ import java.util.Iterator; public class Base_A06Q1 { /** * Program entry point for stack testing. * @param args Argument...

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

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

  • Using Java coding, complete the following: This program should implement a LinkedList data structure to handle...

    Using Java coding, complete the following: This program should implement a LinkedList data structure to handle the management of student records. It will need to be able to store any number of students, using a Linked List. LinearNode.java can be used to aid creating this program Student should be a class defined with the following:    • String name    • int year    • A linked list of college classes (college classes are represented using strings)    • An...

  • Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element...

    Here is the IntegerLinkedList_incomplete class: public class IntegerLinkedList { static class Node { /** The element stored at this node */ private int element; // reference to the element stored at this node /** A reference to the subsequent node in the list */ private Node next; // reference to the subsequent node in the list /** * Creates a node with the given element and next node. * * @param e the element to be stored * @param n...

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

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