Question

Restrictions: You may not change any of the fields, nor the constructor, nor the insertAtFront method....

Restrictions:

  • You may not change any of the fields, nor the constructor, nor the insertAtFront method.

  • As usual, you may not modify the method headers given to you in any way nor may you change

    the name of the class or the package.

  • You must use recursion to solve the problems. Your code may not contain any loops. Functions that have loops will receive 0 points

package hw8;

import java.util.NoSuchElementException;

public class MyList<Item> {

private class MyListNode {

public Item item;

public MyListNode next;

public MyListNode(Item i, MyListNode n) {

item = i;

next = n;

}

}

private MyListNode first;

/**

* Creates an empty list.

*/

public MyList() {

first = null;

}

/**

* Inserts an item at the front of the list

*

* @param item the item to be inserted

*/

public void insertAtFront(Item item) {

MyListNode node = new MyListNode(item, first);

first = node;

}

/**

* Returns the number of items equal to {@code target} in the list

*

* @param target the data item to count

* @return the number of times {@code target} appears in the list

*/

public int count(Item target) {

return countH(first, target);

}

private int countH(MyListNode first, Item target) {

// TODO

return -1;

}

/**

* Returns the data in position {@code index} in the list.

* Note that like arrays the first data item is in position 0.

* @param index the index of the item to get from the list

* @throws NoSuchElementException if the list doesn't have a

* position {@code index}

* @return the data in position {@code index} in the list.

*/

public Item get(int index) {

if (index < 0)

throw new NoSuchElementException();

return getH(first, index);

}

/* Assumes index is not negative */

private Item getH(MyListNode first, int index) {

// TODO

return null;

}

/**

* Constructs a separate copy of a list. Changes to the copy do not affect the original.

* @return the first node of the copy

*/

public MyList<Item> copy() {

MyList<Item> answer = new MyList<Item>();

answer.first = copyH(first);

return answer;

}

/* returns the first node of a copy of the list whose first node is the argument first */

private MyListNode copyH(MyListNode first) {

// TODO

return null;

}

/**

* Constructs a {@code String} representation of the list. The {@code String}

* is a comma separated listing of the {@code String} representations of the items

* in the same order they appear in the list. There are no spaces between items.

* @return a {@code String} representation of the list.

*/

public String convertToString() {

if (first == null)

return "";

return convertToStringH(first);

}

/* Assumes first is not null */

public String convertToStringH(MyListNode first) {

// Hint: for this function, make the base case a list of size 1

// instead of using the empty list as the base case.

// TODO

return null;

}

/**

* Deletes the first occurrence of {@code target} from the list if it is present.

* Does nothing if {@code target} is not present.

*

* @param target the item to be deleted

*/

public void delete(Item target) {

first = deleteH(first, target);

}

/* returns the first node of the modified list */

public MyListNode deleteH(MyListNode first, Item target) {

// TODO

return null;

}

}

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

Please find the required program along with the comments and output:

import java.util.NoSuchElementException;

class MyList<Item> {

    private class MyListNode {

        public Item item;

        public MyListNode next;

        public MyListNode(Item i, MyListNode n) {

            item = i;

            next = n;

        }

    }

    private MyListNode first;

    /**

     * Creates an empty list.

     */

    public MyList() {

        first = null;

    }

    /**

     * Inserts an item at the front of the list

     *

     * @param item the item to be inserted

     */

    public void insertAtFront(Item item) {

        MyListNode node = new MyListNode(item, first);

        first = node;

    }

    /**

     * Returns the number of items equal to {@code target} in the list

     *

     * @param target the data item to count

     * @return the number of times {@code target} appears in the list

     */

    public int count(Item target) {

        return countH(first, target);

    }

    private int countH(MyListNode first, Item target) {

        if(first.next == null)
            return 0;
        else {
            if(first.item == target)
                return 1 + countH(first.next,target);
            else
                return 0 + countH(first.next,target);
        }
        //return -1;
    }

    /**

     * Returns the data in position {@code index} in the list.

     * Note that like arrays the first data item is in position 0.

     * @param index the index of the item to get from the list

     * @throws NoSuchElementException if the list doesn't have a

     * position {@code index}

     * @return the data in position {@code index} in the list.

     */

    public Item get(int index) {

        if (index < 0)

            throw new NoSuchElementException();

        return getH(first, index);

    }

    /* Assumes index is not negative */

    private Item getH(MyListNode first, int index) {

        if(first == null)
            return null;
        else if(index == 1) {
            return first.item;
        }else if(index > 1) {
            return getH(first.next,--index);
        }
        return null;
    }

    /**

     * Constructs a separate copy of a list. Changes to the copy do not affect the original.

     * @return the first node of the copy

     */

    public MyList<Item> copy() {

        MyList<Item> answer = new MyList<Item>();

        answer.first = copyH(first);

        return answer;

    }

    /* returns the first node of a copy of the list whose first node is the argument first */

    private MyListNode copyH(MyListNode first) {

        if(first != null) {
            return new MyListNode(first.item, copyH(first.next));
        }
        return null;

    }

    /**

     * Constructs a {@code String} representation of the list. The {@code String}

     * is a comma separated listing of the {@code String} representations of the items

     * in the same order they appear in the list. There are no spaces between items.

     * @return a {@code String} representation of the list.

     */

    public String convertToString() {

        if (first == null)

            return "";

        return convertToStringH(first);

    }

    /* Assumes first is not null */

    public String convertToStringH(MyListNode first) {

// Hint: for this function, make the base case a list of size 1

// instead of using the empty list as the base case.

        if(first ==  null)
            return "";
        else {
            return first.item + "," + convertToStringH(first.next);
        }
    }

    /**

     * Deletes the first occurrence of {@code target} from the list if it is present.

     * Does nothing if {@code target} is not present.

     *

     * @param target the item to be deleted

     */

    public void delete(Item target) {

        first = deleteH(first, target);

    }

    /* returns the first node of the modified list */

    public MyListNode deleteH(MyListNode first, Item target) {

        if(first != null){

            if(first.item.equals(target)){
                first = first.next;
                return first;
            }else if (first.next.item.equals(target)){
                first.next = first.next.next;
                return first;
            }
            return deleteH(first.next,target);
        }

        return null;

    }
}

public class Test {
    public static void main(String[] args) {

        MyList<String> list = new MyList<>();
        list.insertAtFront("first");
        list.insertAtFront("second");
        list.insertAtFront("third");
        list.insertAtFront("second");
        list.insertAtFront("fourth");
        list.insertAtFront("fifth");
        System.out.println(list.convertToString());

        System.out.println("Count(second) = "+list.count("second"));

        System.out.println("5th element = "+list.get(5));

        list.delete("fourth");
        System.out.println("After deleting 'fourth' in list = "+list.convertToString());
    }
}

------------------------------------------------------------------------------------

OUTPUT:

------------

Add a comment
Know the answer?
Add Answer to:
Restrictions: You may not change any of the fields, nor the constructor, nor the insertAtFront method....
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 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 - I need help creating a method that removes a node at the specific index...

    Java - I need help creating a method that removes a node at the specific index position. The * first node is index 0. public boolean delAt(int index) { src code 2 different classes ******************************************** public class Node { private String data; private Node next; public Node(String data, Node next) { this.data = data; this.next = next; } public Node() { } public String getData() { return data; } public void setData(String data) { this.data = data; } public void...

  • Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface:...

    Part I: Create a doubly linked circular list class named LinkedItemList that implements the following interface: /** * An ordered list of items. */ public interface ItemList<E> {      /**       * Append an item to the end of the list       *       * @param item – item to be appended       */ public void append(E item);      /**       * Insert an item at a specified index position       *       * @param item – item to be...

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

  • Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac...

    Can someone help me to figure that error I have put below. JAVA ----jGRASP exec: javac -g P4Program.java P4Program.java:94: error: package list does not exist Iterator i = new list.iterator(); ^ 1 error ----jGRASP wedge2: exit code for process is 1. ----jGRASP: operation complete. Note: Below there are two different classes that work together. Each class has it's own fuctions/methods. import java.util.*; import java.io.*; public class P4Program{ public void linkedStackFromFile(){ String content = new String(); int count = 1; File...

  • Java/LinkedList Need help with a few of the TODO parts, more info below in comments in...

    Java/LinkedList Need help with a few of the TODO parts, more info below in comments in bold. Thanks, package lab4; import java.util.IdentityHashMap; public class IntNode implements Cloneable {    private int data;    private IntNode next;       public IntNode(int d, IntNode n) {        data = d;        next = n;    }       public IntNode getNext() {        return next;    }          /// Override methods from Object       @Override   ...

  • JAVA: * You may not add any fields to the node or list classes. * You...

    JAVA: * You may not add any fields to the node or list classes. * You may not add any methods to the node class. * Do not change any 'Utility' methods that I have included. * You may NOT use any arrays or other Java classes ~ Testing purposes ~ public class DSIList {    Node first,last;        // three instance variables    int N;                   // maintain the size of the list    static class Node...

  • Complete the implementation of the method replace: public class SinglyLinkedList private Node head, public SinglyLinkedListo this(null) public SinglyLinkedList(Node head) [ this.head -head public Nod...

    Complete the implementation of the method replace: public class SinglyLinkedList private Node head, public SinglyLinkedListo this(null) public SinglyLinkedList(Node head) [ this.head -head public Node getHeado return head public void setHead(Node head) [ head: this. head Method that creates a Node containing 'item' @param item Value to be added this.headnew Node(item, this.head) * and adds it as the first element in the list *I public void add(int item) Method that finds the node at the given index d replaces its value...

  • Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given reference...

    Data Structures - Singly Linked Lists You will add a method swapNodes to SinglyLinkedList class (below). This method should swap two nodes node1 and node2 (and not just their contents) given references only to node1 and node2. The new method should check if node1 and node2 are the same node, etc. Write the main method to test the swapNodes method. You may need to traverse the list. package linkedlists; public class SinglyLinkedList<E> implements Cloneable {    // ---------------- nested Node class...

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

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