From c9b6b9a5ca082fe7c1b6f58d7713f785a9eb6a5c Mon Sep 17 00:00:00 2001 From: Martial Simon Date: Mon, 15 Sep 2025 01:08:27 +0200 Subject: add: graphs et rushs --- .../fr/epita/assistants/linkedlist/LinkedList.java | 99 ++++++++++++++++++++++ 1 file changed, 99 insertions(+) create mode 100644 graphs/java/linkedList/src/main/java/fr/epita/assistants/linkedlist/LinkedList.java (limited to 'graphs/java/linkedList/src/main') diff --git a/graphs/java/linkedList/src/main/java/fr/epita/assistants/linkedlist/LinkedList.java b/graphs/java/linkedList/src/main/java/fr/epita/assistants/linkedlist/LinkedList.java new file mode 100644 index 0000000..c54f0f4 --- /dev/null +++ b/graphs/java/linkedList/src/main/java/fr/epita/assistants/linkedlist/LinkedList.java @@ -0,0 +1,99 @@ +package fr.epita.assistants.linkedlist; + +public class LinkedList> { + static public class ListElement { + T value; + ListElement next; + + public ListElement(T value) { + this.value = value; + this.next = null; + } + } + + /** + * Initializes the list + **/ + public ListElement head; + public int size; + public LinkedList() { + this.head = new ListElement(null); + this.size = 0; + } + + /** + * Inserts the specified element into the list. + * The elements must be sorted in ascending order. + * null elements should be at the end of the list. + * + * @param e Element to be inserted + **/ + public void insert(T e) { + ListElement h = this.head; + while ((h.next != null) && (h.next.value.compareTo(e) < 0)) + h = h.next; + + if (h.next == null) + h.next = new ListElement(e); + else + { + ListElement tmp = h.next; + h.next = new ListElement<>(e); + h.next.next = tmp; + } + this.size++; + } + + /** + * Returns the n-th element in the list. + * + * @param i Index + * @return The element at the given index + * @throws IndexOutOfBoundsException if there is no element at this + * index. + **/ + public T get(int i) { + if (i >= this.size || i < 0) + throw new IndexOutOfBoundsException(); + ListElement h = this.head; + while(i-- != 0) + h = h.next; + return h.next.value; + } + + /** + * Removes the first occurrence of the specified element in the list. + * + * @param e Element to remove + * @return returns the element that has been removed or null + **/ + public T remove(T e) { + ListElement h = this.head; + while ((h.next != null) && (h.next.value.compareTo(e) != 0)) + h = h.next; + if (h.next == null) + return null; + ListElement res = h.next; + h.next = h.next.next; + res.next = null; + this.size--; + return res.value; + } + + /** + * Returns the size of the list. + * + * @return Number of elements in the list + **/ + public int size() { + return this.size; + } + + /** + * Removes all elements from the list. + **/ + public void clear() { + this.head.next = null; + this.size = 0; + } +} \ No newline at end of file -- cgit v1.2.3