diff --git a/app/src/main/java/ru/project/collection/MyLinkedList.java b/app/src/main/java/ru/project/collection/MyLinkedList.java new file mode 100644 index 0000000..23b2b75 --- /dev/null +++ b/app/src/main/java/ru/project/collection/MyLinkedList.java @@ -0,0 +1,123 @@ +import java.util.Arrays; +public class MyLinkedList implements MyList +{ + private Node head; + private int size; + public void add(T value) { + if (head == null) { + this.head = new Node<>(value); + } else { + Node temp = head; + while (temp.getNext() != null) { + temp = temp.getNext(); + } + temp.setNext(new Node<>(value)); + } + size++; + } + public T get(int index) + { + int currentIndex = 0; + Node temp = head; + while(temp != null) + { + if (currentIndex == index) + { + return temp.getValue(); + + } + else { + temp = temp.getNext(); + currentIndex++; + } + + } + throw new IllegalArgumentException(); + } + public void remove(int index) + { + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + if (index == 0) + { + head = head.getNext(); + size--; + return; + + } + int currentIndex = 0; + Node temp = head; + while (temp != null) + { + if (currentIndex == index-1) + { + temp.setNext(temp.getNext().getNext()); + size--; + return; + } + else { + temp = temp.getNext(); + currentIndex++; + } + } + } + public T set(int index, T value) { + if (index < 0 || index >= size) { + throw new IllegalArgumentException(); + } + + Node temp = head; + for (int i = 0; i < index; i++) { + temp = temp.getNext(); + } + + T oldValue = temp.getValue(); + temp.setValue(value); + return oldValue; + } + public int size() { + return size; + } + public boolean isEmpty() + { + return size == 0; + } + @Override + public String toString() { + Object[] res = new Object[size]; + int index = 0; + Node temp = head; + while (temp != null) { + res[index] = temp.getValue(); + index++; + temp = temp.getNext(); + } + return Arrays.toString(res); + } + + private static class Node { + private T value; + private Node next; + + public Node(T value) { + this.value = value; + } + + public void setValue(T value) { + this.value = value; + } + + public void setNext(Node next) { + this.next = next; + } + + public T getValue() { + return value; + } + + public Node getNext() { + return next; + } + } +} \ No newline at end of file diff --git a/app/src/main/java/ru/project/collection/MyList.java b/app/src/main/java/ru/project/collection/MyList.java new file mode 100644 index 0000000..bd47567 --- /dev/null +++ b/app/src/main/java/ru/project/collection/MyList.java @@ -0,0 +1,16 @@ +package ru.project.collection; + +public interface MyList { + + void add(T element); + + T get(int index); + + T set(int index, T element); + + void remove(int index); + + int size(); + + boolean isEmpty(); +}