Last active
April 17, 2024 18:48
-
-
Save Delors/3c341f89fbff903b0f9b35201d299075 to your computer and use it in GitHub Desktop.
A very basic implementation of a doubly linked list.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package code; | |
public class DoublyLinkedList<E> { | |
private static class Node<E> { | |
E value; | |
Node<E> next; | |
Node<E> previous; | |
} | |
private Node<E> head; | |
private Node<E> last; | |
public DoublyLinkedList() { | |
head = null; | |
last = null; | |
} | |
public void prepend(E value) { | |
Node<E> newNode = new Node<>(); | |
newNode.value = value; | |
if (head == null) { | |
head = last = newNode; | |
} else { | |
newNode.next = head; | |
this.head.previous = newNode; | |
this.head = newNode; | |
} | |
} | |
public void append(E value) { | |
var newNode = new Node<E>(); | |
newNode.value = value; | |
if (head == null) { | |
head = last = newNode; | |
} else { | |
newNode.previous = this.last; | |
this.last.next = newNode; | |
this.last = newNode; | |
} | |
} | |
public boolean isEmpty() { | |
return head == null; | |
} | |
public String toString() { | |
var r = ""; | |
Node<E> current = last; | |
while (current != null) { | |
r += current.value; | |
current = current.previous; | |
} | |
return r; | |
} | |
public static void main(String[] args) { | |
DoublyLinkedList<String> ls = new DoublyLinkedList<>(); | |
ls.append("Dies "); | |
ls.append("ist "); | |
ls.append("ein "); | |
ls.append("Test "); | |
ls.prepend("Text: "); | |
/* | |
// after implementing "remove(int index)": | |
System.out.println(ls); // Test ein ist Dies Text: | |
ls.remove(0); | |
System.out.println(ls); // Test ein ist Dies | |
ls.remove(1); | |
System.out.println(ls); // Test ein Dies | |
ls.remove(2); | |
System.out.println(ls); // ein Dies | |
ls.remove(0); | |
System.out.println(ls); // ein | |
ls.remove(0); | |
System.out.println(ls); // | |
*/ | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment