Java Linked List Implementation: Essential Methods
Classified in Computers
Written on in
English with a size of 2.81 KB
Java Linked List Implementation
Inserting Elements at Positions
public void insertPos() {
if (isEmpty()) {
throw new EmptyCollectionException("Lista");
} else {
LinearNode actual = first;
LinearNode nuevo = null;
int posActual = 1;
while (actual != null) {
nuevo = new LinearNode(posActual);
nuevo.next = actual.next;
actual.next = nuevo;
actual = nuevo.next;
nElements++;
posActual++;
}
}
}Skipping Iterator Implementation
private class SkippingIteratorImpl implements Iterator<T> {
private Node<T> current;
public SkippingIteratorImpl() {
current = first;
if (first != null) {
current = first.next;
}
}
@Override
public boolean hasNext() {
return (current != null);
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
T elemento = current.element;
current = current.next;
if (current != null) {
current = current.next;
}
return elemento;
}
}Removing the Penultimate Element
public T eliminarPenult() throws EmptyCollectionException {
T result;
if (first == null) {
throw new EmptyCollectionException("Lista vacia");
} else if (first.next == null) {
result = first.element;
first = null;
} else if (first.next.next == null) { // 2 elementos
result = first.element;
first = first.next;
} else { // Tiene mas de dos elementos
Node<T> antepenul = first;
Node<T> penultimo = first.next;
while (penultimo.next.next != null) {
antepenul = antepenul.next;
penultimo = penultimo.next;
}
result = penultimo.element;
antepenul.next = penultimo.next;
}
return result;
}Reordering the First Element
public void recolocaPrim() throws EmptyCollectionException {
if (header == null) throw new EmptyCollectionException("");
if (header != tail) {
if (header.next == tail) {
// Dos elementos
tail = header;
header = header.next;
header.next = tail;
header.previous = null;
tail.previous = header;
tail.next = null;
} else {
// Caso general
DoubleNode aux = header;
header = header.next;
header.previous = null;
DoubleNode penultimo = tail.previous;
aux.next = tail;
aux.previous = penultimo;
tail.previous = aux;
penultimo.next = aux;
}
}
}