BRUH

 avatar
unknown
plain_text
2 years ago
2.8 kB
3
Indexable
import java.util.NoSuchElementException;

public class MyLinkedList implements MyList {
    private Node head;
    private int size;

    public void addToEnd(Object obj) {
        Node newNode = new Node(obj);
        if (head == null) {
            head = newNode;
        } else {
            Node current = head;
            while (current.next != null) {
                current = current.next;
            }
            current.next = newNode;
        }
        size++;
    }

    public void insertAt(int index, Object obj) {
        if (index < 0 || index > size) {
            throw new NoSuchElementException("Index: " + index + ", Size: " + size);
        }

        Node newNode = new Node(obj);
        if (index == 0) {
            newNode.next = head;
            head = newNode;
        } else {
            Node current = head;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }
            newNode.next = current.next;
            current.next = newNode;
        }
        size++;
    }

    public void removeAt(int index) {
        if (index < 0 || index >= size) {
            throw new NoSuchElementException("Index: " + index + ", Size: " + size);
        }
        if (index == 0) {
            head = head.next;
        } else {
            Node current = head;
            for (int i = 0; i < index - 1; i++) {
                current = current.next;
            }
            current.next = current.next.next;
        }
        size--;
    }

    public Object getAt(int index) {
        if (index < 0 || index >= size) {
            throw new NoSuchElementException("Index: " + index + ", Size: " + size);
        }
        Node current = head;
        for (int i = 0; i < index; i++) {
            current = current.next;
        }
        return current.data;
    }

    public int getSize() {
        return size;
    }

    public MyListIterator getIterator() {
        return new LinkedListIterator();
    }

    private class Node {
        private Object data;
        private Node next;

        public Node(Object data) {
            this.data = data;
            this.next = null;
        }
    }

    private class LinkedListIterator implements MyListIterator {
        private Node current;

        public LinkedListIterator() {
            current = head;
        }

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

        public Object next() {
            if (!hasNext()) {
                throw new NoSuchElementException();
            }
            Object data = current.data;
            current = current.next;
            return data;
        }
    }
}
Editor is loading...