Question

/** * Notes: * You must use RECURSION to solve the problems. Your code may not...

/**
* Notes:
* You must use RECURSION to solve the problems. Your code may not contain any loops.
* You may not change any of the fields, nor the constructor, nor the insertAtFront method.
* 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.
*/

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;
   }
}
// ===== JUNIT TEST =====

package hw8;
import java.util.NoSuchElementException;
import static org.junit.Assert.*;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.Timeout;

public class HW6Test {   
   @Rule
public Timeout globalTimeout = Timeout.seconds(1);
   private static MyList<Integer> makeIntList(int[] a) {
       MyList<Integer> result = new MyList<Integer>();
       for(int i = a.length-1; i >= 0; i--) {
           result.insertAtFront(a[i]);
       }
       return result;
   }
   private static MyList<String> makeStringList(String[] a) {
       MyList<String> result = new MyList<String>();
       for(int i = a.length-1; i >= 0; i--) {
           result.insertAtFront(a[i]);
       }
       return result;
   }
   @Test
   public void test10CountBasic() {
       MyList<String> list = new MyList<String>();
       assertEquals(0, list.count("hello"));
       assertEquals(0, list.count(""));
       list.insertAtFront("hello");
       assertEquals(1, list.count("hello"));
       assertEquals(0, list.count(""));
   }
   @Test
   public void test10GetBasic() {
       String[] a = {"1", "3", "5", "2", "4"};
       MyList<String> list = makeStringList(a);
       assertEquals("1", list.get(0));
       assertEquals("3", list.get(1));
       assertEquals("5", list.get(2));
       assertEquals("2", list.get(3));
       assertEquals("4", list.get(4));
   }
   @Test
   public void test05GetOutOfBounds() {
       String[] a1 = {"45", "9", "18", "3", "5", "9", "88", "5", "3", "9", "2"};
       String[] a2 = {"1", "3", "5", "2", "4"};
       MyList<String> l1 = new MyList<String>();
       try {
           l1.get(0);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
       l1 = makeStringList(a1);
       MyList<String> l2 = makeStringList(a2);
       try {
           l1.get(-2);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
       try {
           l1.get(11);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
       try {
           l2.get(11);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
       try {
           l2.get(5);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
       try {
           l2.get(-1);
           fail("Failed to generate exception");
       } catch (NoSuchElementException e) {}
   }
   @Test
   public void test05CopyBasic1() {
       MyList<Integer> l1 = new MyList<Integer>();
       l1.insertAtFront(5);
       MyList<Integer> l2 = l1.copy();
       assertEquals(5, l1.get(0).intValue());
       assertEquals(5, l2.get(0).intValue());
   }

   @Test
   public void test05ConvertToStringBasic() {
       MyList<String> list = new MyList<String>();
       list.insertAtFront("4");
       assertEquals("4", list.convertToString());
       list.insertAtFront("9");
       assertEquals("9,4", list.convertToString());
       list.insertAtFront("0");
       assertEquals("0,9,4", list.convertToString());
   }
   @Test
   public void test05ConvertToStringEmpty() {
       MyList<String> list = new MyList<String>();
       assertEquals("", list.convertToString());
   }
   @Test
   public void test05ConvertToStringSizeOne() {
       MyList<String> list = new MyList<String>();
       list.insertAtFront("4");
       assertEquals("4", list.convertToString());
   }
}
@Test
   public void test05DeleteBasic() {
       MyList<String> list = new MyList<String>();
       list.insertAtFront("7");
       list.insertAtFront("2");
       list.delete("7");
       assertEquals("2", list.get(0));
       assertEquals(0, list.count("7"));
   }
   @Test
   public void test05DeleteMissing() {
       MyList<String> list = new MyList<String>();
       list.insertAtFront("8");
       list.insertAtFront("7");
       list.insertAtFront("1");
       list.delete("5");
       assertEquals("1", list.get(0));
       assertEquals("7", list.get(1));
       assertEquals("8", list.get(2));
   }

}

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


public class MyList<Item>
{
    public final int DEFAULT_SIZE = 10;
    private int size;
    private Item[] array;

    public MyList()
    {
        this.array = (Item[]) new Object[DEFAULT_SIZE];
        this.size = 0;
    }

    public int getSize()
    {
        return size;
    }

    public void setSize(int size)
    {
        this.size = size;
    }

    public void set(int index, Item t)
    {
        array[index] = t;
    }

    public void add(int index, Item t)
    {
        if (index < 0 || index > getSize())
        {
            throw new IndexOutOfBoundsException();
        }
        // Assume available space
        if (index == 0 || index == getSize())
        {
            set(index, t);
        } else
        {
            putend(index, getSize() - 1);
            set(index, t);
        }
        this.setSize(getSize() + 1);
    }

    private void putend(int index, int current)
    {
        if (current >= index)
        {
            array[current + 1] = array[current];
            putend(index, current - 1);
        }
    }

    public Item remove(int index)
    {
        T result = array[index];
        putstart(index + 1);
        this.setSize(getSize() - 1);
        return result;
    }

    private void putstart(int current)
    {
        array[current - 1] = array[current];
      
        if (current == getSize())
        {
            set(current, null);
        } else
        {
            putstart(current + 1);
        }
    }

    public String toString()
    {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        toString(0, sb);
        sb.append("]");
        String s = sb.toString();
        return s;
    }

    private void toString(int index, StringBuilder sb)
    {
        if (index < getSize() - 1)
        {
            sb.append(array[index] + ",");
            toString(index + 1, sb);
        } else if (index < getSize())
        {
            sb.append(array[index]);
        }
    }

}

Add a comment
Know the answer?
Add Answer to:
/** * Notes: * You must use RECURSION to solve the problems. Your code may not...
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
  • 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...

  • For this assignment, you will write a program to work with Huffman encoding. Huffman code is...

    For this assignment, you will write a program to work with Huffman encoding. Huffman code is an optimal prefix code, which means no code is the prefix of another code. Most of the code is included. You will need to extend the code to complete three additional methods. In particular, code to actually build the Huffman tree is provided. It uses a data file containing the frequency of occurrence of characters. You will write the following three methods in the...

  • Please help complete the items marked TODO in the code and get the tests to pass:...

    Please help complete the items marked TODO in the code and get the tests to pass: import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; public class TestIterator { private List<Integer> list; // See the Java List Interface documentation to understand what all the List methods do ... @Before public void setUp() throws Exception { list = new ArrayList<Integer>(); // TODO also try with a...

  • NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT...

    NO ONE HAS PROVIDED THE CORRECT CODE TO PROVIDE THE GIVEN OUTPUT. PLEASE PROVIDE CODE THAT WOULD CAUSE THE HW1.java TO PRINT THE RIGHT DATA.!!! The LinkedList class implements both the List interface and the Stack interface, but several methods (listed below) are missing bodies. Write the code so it works correctly. You should submit one file, LinkedList.java. Do not change the interfaces. Do not change the public method headers. Do not rename the LinkedList class. None of your methods...

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

  • SELF-CHECK Why did the first version of method search that passed the first test itemNotFirstElementInSingleElementArray contain...

    SELF-CHECK Why did the first version of method search that passed the first test itemNotFirstElementInSingleElementArray contain only the statement return −1? Assume the first JUnit test for the findLargest method described in Self-Check exercise 2 in section 3.4 is a test that determines whether the first item in a one element array is the largest. What would be the minimal code for a method findLargest that passed this test? PROGRAMMING Write the findLargest method described in self-check exercise 2 in...

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

  • You must use an array to hold the items in the queue. In other words, one...

    You must use an array to hold the items in the queue. In other words, one of your fields should be an array for holding the items, but you may not have any other container fields (no other arrays, lists, stacks, queues, etc.) You will need at least one additional field (an int). package hw5; public class GeneralizedQueue {    /** * Creates an empty queue. */ public GeneralizedQueue() { // TODO }    /** * Checks if the queue...

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

  • Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong...

    Develop a Generic String List (GSL). NOTE: I have done this lab but someting is wrong here is what i was told that was needed. Ill provide my code at the very end. Here is what is missing : Here is my code: public class GSL { private String arr[]; private int size; public GSL() {     arr = new String[10];     size = 0; } public int size() {     return size; } public void add(String value) {    ...

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