Testat Sammlung
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

152 lines
3.1 KiB

package solution;
public class SimpleLinkedList<E> extends AbstractSimpleList<E> {
Node<E> firstNode;
int size;
public SimpleLinkedList() {
firstNode = null;
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public boolean add(E e) {
if (e == null) {
return false;
} else if (firstNode == null) {
firstNode = new Node<E>(e);
} else {
Node<E> currentNode = firstNode;
while (currentNode != null) {
if (currentNode.getSuccessor() == null) {
break;
}
currentNode = currentNode.getSuccessor();
}
Node<E> newNode = new Node<E>(e);
currentNode.setSuccessor(newNode);
newNode.setPredecessor(currentNode);
}
size++;
return true;
}
@Override
public boolean remove(Object o) {
if (o == null) {
return false;
}
Node<E> currentNode = firstNode;
while (currentNode != null) {
if (o.equals(currentNode.getPayload())) {
currentNode.setPayload(null);
size--;
return true;
}
if (currentNode.getSuccessor() == null) {
break;
}
currentNode = currentNode.getSuccessor();
}
return false;
}
@Override
public boolean contains(Object o) {
if (o == null) {
return false;
}
Node<E> currentNode = firstNode;
while (currentNode != null) {
if (o.equals(currentNode.getPayload())) {
return true;
}
currentNode = currentNode.getSuccessor();
}
return false;
}
@Override
public void forAll(ICommand<E> command) {
if (command != null) {
Node<E> currentNode = firstNode;
while (currentNode != null) {
command.execute(currentNode.getPayload());
currentNode = currentNode.getSuccessor();
}
}
}
private Node<E> getIndex(int i) {
if (i < 0 || size <= i) {
return null;
}
Node<E> currentNode = firstNode;
int currentIndex = 0;
while (currentNode != null) {
if (currentIndex >= i) {
if (currentNode.getPayload() != null) {
return currentNode;
}
}
currentNode = currentNode.getSuccessor();
currentIndex++;
}
return null;
}
public E get(int i) throws IndexOutOfBoundsException {
return getIndex(i).getPayload();
}
public void set(int i, E e) throws IndexOutOfBoundsException {
getIndex(i).setPayload(e);
}
public boolean remove(int i) throws IndexOutOfBoundsException {
if (getIndex(i) != null) {
getIndex(i).setPayload(null);
size--;
return true;
}
return false;
}
public void add(int i, E e) throws IndexOutOfBoundsException {
if (size == 0) {
if (i != 0) {
throw new IndexOutOfBoundsException("Index " + i + " is out of bounds!");
}
set(0, e);
} else if (i == size) {
add(e);
} else if (size > 0 && i < size) {
Node<E> newNode = new Node<>(e);// node3
Node<E> tempNode = getIndex(i); // node2
Node<E> preTempNode = getIndex(i).getPredecessor(); // node1
preTempNode.setSuccessor(newNode);
newNode.setPredecessor(preTempNode);
newNode.setSuccessor(tempNode);
tempNode.setPredecessor(newNode);
}
}
}