diff options
Diffstat (limited to 'graphs/java/linkedList/src/main')
| -rw-r--r-- | graphs/java/linkedList/src/main/java/fr/epita/assistants/linkedlist/LinkedList.java | 99 |
1 files changed, 99 insertions, 0 deletions
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<T extends Comparable<T>> { + static public class ListElement<T> { + T value; + ListElement<T> next; + + public ListElement(T value) { + this.value = value; + this.next = null; + } + } + + /** + * Initializes the list + **/ + public ListElement<T> head; + public int size; + public LinkedList() { + this.head = new ListElement<T>(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<T> h = this.head; + while ((h.next != null) && (h.next.value.compareTo(e) < 0)) + h = h.next; + + if (h.next == null) + h.next = new ListElement<T>(e); + else + { + ListElement<T> 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<T> 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<T> h = this.head; + while ((h.next != null) && (h.next.value.compareTo(e) != 0)) + h = h.next; + if (h.next == null) + return null; + ListElement<T> 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 |
