📚 The CoCalc Library - books, templates and other resources
cocalc-examples / martinthoma-latex-examples / presentations / Programmieren-Tutorium / Tutorium-09 / SinglyLinkedList-Result / SinglyLinkedList.java
132939 viewsLicense: OTHER
public class SinglyLinkedList<E> {1private Node<E> head;23/**4* Add an object to the list.5*6* @param object the element you want to add7*/8public void add(E object) {9Node<E> newNode = new Node<E>(object);10newNode.setNext(head);11head = newNode;12}1314/**15* Check if object is in is in the SinglyLinkedList16*17* @param object the object you want to search18* @return the bike, if you found it, otherwise {@code null}19*/20public boolean contains(E object) {21Node<E> currentNode = head;2223while (currentNode != null && currentNode.getElement().equals(object)) {24currentNode = currentNode.getNext();25}2627return currentNode != null;28}2930/**31* Get a bike.32*33* @param bike the bike you want to get34* @return35*/36public E get(E bike) {37if (contains(bike)) {38Node<E> currentNode = head;39while (currentNode.getElement() != bike) {40currentNode = currentNode.getNext();41}42return bike;43} else {44return null;45}46}4748/**49* Remove bike from the SinglyLinkedList, if it exists.50*51* @param bike the bike you want to search52* @return {@code bike} if it is in SinglyLinkedList, otherwise {@code null}53*/54public E remove(E bike) {55if (!contains(bike)) {56return null;57} else if (head.getElement() == bike) {58head = head.getNext();59return bike;60} else {61// Knoten und Vorgängerknoten finden62Node<E> previousNode = head;63Node<E> currentNode = head;6465while (currentNode.getElement() != bike) {66previousNode = currentNode;67currentNode = currentNode.getNext();68}6970// Zeiger umbiegen71previousNode.setNext(currentNode.getNext());72return bike;73}74}7576/**77* Print all bikes in SinglyLinkedList.78*/79public void printBikes() {80Node<E> currentNode = head;81System.out.print("start -> ");82while (currentNode != null) {83System.out.print(currentNode);84System.out.print(" -> ");85currentNode = currentNode.getNext();86}87System.out.println("null");88}89}909192