|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596 |
- import java.util.Iterator;
-
- class LenkeListe<E extends Comparable<E>> implements Iterable<E> {
- public Node first;
- public Node last;
-
- public class Node<T extends Comparable<T>> {
- public Node next;
- public Node prev;
- public E val;
-
- Node(E val) {
- this.val = val;
- }
- }
-
- public boolean tom() {
- return first == null;
- }
-
- public void leggTil(E val) {
- Node<E> n = new Node<>(val);
-
- if (first == null)
- first = n;
-
- if (last == null) {
- last = n;
- } else {
- n.prev = last;
- last.next = n;
- last = n;
- }
- }
-
- public void fjernMinste() {
- Node smallest = first;
- Node n = first;
-
- while (n != null) {
- if (n.val.compareTo(smallest.val) < 0) {
- smallest = n;
- }
- n = n.next;
- }
-
- fjern(smallest);
- }
-
- public boolean inneholder(E val) {
- for (E e: this) {
- if (e.compareTo(val) == 0)
- return true;
- }
-
- return false;
- }
-
- public void fjern(Node n) {
- n.prev.next = n.next;
- n.next.prev = n.prev;
- if (n == first) {
- first = n.next;
- }
- if (n == last) {
- last = n.prev;
- }
- }
-
- private class ListIterator<T extends Comparable<T>> implements Iterator<T> {
- private Node nextNode = first;
-
- @Override
- public boolean hasNext() {
- return nextNode != null;
- }
-
- @Override
- public T next() {
- Node n = nextNode;
- nextNode = n.next;
- return (T)n.val;
- }
-
- @Override
- public void remove() {
- throw new UnsupportedOperationException();
- }
- }
-
- //Iterator, foreach loops
- @Override
- public Iterator<E> iterator() {
- return new ListIterator<E>();
- }
- }
|