Data Structures in Java: Programming Assignment 3 ArrayLists and LinkedLists

Data Structures in Java: Programming Assignment 3
ArrayLists and LinkedLists

  1. Objective
    Your goal is to implement additional methods found in the MyList interface. These methods
    will be implemented in both MyArrayList and MyLinkedList classes. In doing so, you will gain
    a better understanding of the similarities and differences between the two data structures.
  2. Problem
    Download the following files from CourseWorks:
    • MyArrayList.java
    • MyLinkedList.java
    • MyList.java (found in the assignment description itself)

There are 6 new methods in the MyList interface. You need to implement them in
MyArrayList.java and MyLinkedList.java.

/** 
 * Returns a string representation of the list. The string will begin with 
 * a '[' and end with a ']'. Inside the square brackets will be a comma- 
 * separated list of values, such as [Brian, Susan, Jamie]. 
 * @return a string representation of the list. 
 */ 
@Override 
String toString(); 

/** 
 * Inserts the specified element at the specified position in this list. 
 * Shifts the element currently at that position (if any) and any subsequent 
 * elements to the right (adds one to their indices). 
 * @param index    index at which the specified element is to be inserted 
 * @param element  element to be inserted 
 * @throws IndexOutOfBoundsException if the index is out of range 
 *         (index < 0 || index > size()) 
 * The exception message must be: 
 * "Index: " + index + ", list size: " + size 
 */ 
void add(int index, E element); 

/** 
 * Removes the element at the specified position in this list. 
 * @param index  the index of the element to be removed 
 * @return the element that was removed from the list 
 * @throws IndexOutOfBoundsException if the index is out of range 
 *         (index < 0 || index >= size()) 
 * The exception message must be: 
 * "Index: " + index + ", list size: " + size 
 */ 
E remove(int index); 

/** 
 * Returns the index of the first occurrence of the specified element in 
 * this list, or -1 if this list does not contain the element. More 
 * formally, returns the lowest index i such that Objects.equals(o, get(i)), 
 * or -1 if there is no such index. 
 * @param element element to search for 
 * @return the index of the first occurrence of the specified element in 

Lists - 2

  • this list, or -1 if this list does not contain the element
    /
    int indexOf(E element);
    /
    *
  • Returns an array of indexes of each occurrence of the specified element
  • in this list, in ascending order. If the specified element is not found,
  • a non-null empty array (not null) is returned.
  • @param element element to search for
  • @return an array of each occurrence of the specified element in this
  • list
    /
    int[] indexesOf(E element);
    /
    *
  • Reverses the data in the list.
  • For MyArrayList, the data inside the underlying array is moved. For
  • MyLinkedList, the tail must become the head, and all the pointers are
  • reversed. Both implementations must run in Theta(n).
    */
    void reverse();
  1. Tips
    You must test your work thoroughly. Junit tests have been provided for you, but they are
    not comprehensive. You are responsible for ensuring your code works for edge cases. If
    your code does not compile, you will earn a 0. You will earn points for test cases that pass
    and follow the specifications described in the Javadoc comments.
  2. Submission
    Create a zip file called hw3.zip containing:
    • MyArrayList.java
    • MyLinkedList.java
    • MyList.java
    Do not put your code in a Java package or submit extraneous files or folders. Upload your
    submission to Canvas. Only the final submission will be graded.
import java.util.Iterator;

/**
 * Linked list implementation of the MyList interface.
 * @author Brian S. Borowski
 * @version 1.0 September 27, 2022
 */
public class MyLinkedList<E> implements MyList<E> {
    private Node head, tail;
    private int size;

    /**
     * Constructs an empty list.
     */
    public MyLinkedList() {
        head = tail = null;
        size = 0;
    }

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

    /**
     * Returns true if this list contains no elements.
     * @return true if this list contains no elements
     */
    public boolean isEmpty() {
        return size == 0;
    }

    /**
     * Replaces the element at the specified position in this list with the
     * specified element.
     * @param index    index of the element to return
     * @param element  element to be stored at the specified position
     * @return  the element at the specified position in this list
     * @throws  IndexOutOfBoundsException - if the index is out of range
     *          (index < 0 || index >= size())
     */
    public E set(int index, E element) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException(
                    "Index: " + index + ", list size: " + size);
        }
        Node p = head;
        for (int i = 0; i < index; i++, p = p.next);
        E oldElement = p.element;
        p.element = element;
        return oldElement;
    }

    /**
     * Returns the element at the specified position in this list.
     * @param index  index of the element to return
     * @return       the element at the specified position in this list
     * @throws       IndexOutOfBoundsException - if the index is out of range
     *               (index < 0 || index >= size())
     */
    public E get(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException(
                    "Index: " + index + ", list size: " + size);
        }
        Node p = head;
        for (int i = 0; i < index; i++, p = p.next);
        return p.element;
    }

    /**
     * Appends the specified element to the end of this list.
     * @param element  element to be appended to this list
     * @return true
     */
    public boolean add(E element) {
        Node n = new Node(element);
        if (head == null) {
            head = tail = n;
        } else {
            tail.next = n;
            tail = n;
        }
        size++;
        return true;
    }

    /**
     * Removes all of the elements from this list.
     */
    public void clear() {
        head = tail = null;
        size = 0;
    }

    public Iterator<E> iterator() {
        return new ListItr();
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");

        Node current = head;
        while (current != null) {
            sb.append(current.element);
            if (current.next != null) {
                sb.append(", ");
            }
            current = current.next;
        }

        sb.append("]");
        return sb.toString();
    }
    @Override
    public void add(int index, E element) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", list size: " + size);
        }

        if (index == size) {
            // Adding at the end of the list, equivalent to the add(E element) method
            add(element);
        } else {
            Node newNode = new Node(element);
            if (index == 0) {
                // Adding at the beginning of the list
                newNode.next = head;
                head = newNode;
            } else {
                // Adding in the middle of the list
                Node previous = getNode(index - 1);
                newNode.next = previous.next;
                previous.next = newNode;
            }
            size++;
        }
    }

    @Override
    public E remove(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", list size: " + size);
        }

        E removedElement;
        if (index == 0) {
            // Removing the first element
            removedElement = head.element;
            head = head.next;
            if (head == null) {
                tail = null; // List is now empty
            }
        } else {
            Node previous = getNode(index - 1);
            Node current = previous.next;
            removedElement = current.element;
            previous.next = current.next;
            if (current == tail) {
                tail = previous; // Removed the last element
            }
        }
        size--;
        return removedElement;
    }

    @Override
    public int indexOf(E element) {
        Node current = head;
        int index = 0;

        while (current != null) {
            if (element.equals(current.element)) {
                return index;
            }
            current = current.next;
            index++;
        }

        return -1; // Element not found
    }

    @Override
    public int[] indexesOf(E element) {
        int[] indexes = new int[size];
        int count = 0;
        int index = 0;
        Node current = head;

        while (current != null) {
            if (element.equals(current.element)) {
                indexes[count++] = index;
            }
            current = current.next;
            index++;
        }

        int[] result = new int[count];
        System.arraycopy(indexes, 0, result, 0, count);

        return result;
    }

    @Override
    public void reverse() {
        Node current = head;
        Node previous = null;
        Node next = null;

        while (current != null) {
            next = current.next;
            current.next = previous;
            previous = current;
            current = next;
        }

        // Swap head and tail
        Node temp = head;
        head = tail;
        tail = temp;
    }


    private class ListItr implements Iterator<E> {
        private Node current;

        ListItr() {
            current = head;
        }

        @Override
        public boolean hasNext() {
            return current != null;
        }

        @Override
        public E next() {
            E element = current.element;
            current = current.next;
            return element;
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    }

    /**
     * Returns the Node at the specified index in this list.
     * @param index  index of the Node to return
     * @return       the Node at the specified index in this list
     * @throws       IndexOutOfBoundsException - if the index is out of range
     *               (index < 0 || index >= size())
     */
    private Node getNode(int index) {
        if (index < 0 || index >= size) {
            throw new IndexOutOfBoundsException("Index: " + index + ", list size: " + size);
        }

        Node current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }

        return current;
    }


    private class Node {
        Node next;
        E element;

        public Node(E element) {
            this.element = element;
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值