Не совсем понимаю как работает конструктор с переменной first.next. Получается, что он в самом начале добавляет в нее ссылку на last и в дальнейшем нигде ее не меняет, т.е. у нас первая переменная остается со ссылкой на самый последний элемент, вместо того чтобы иметь ссылку на 2ой элемент...или это не так?
public class StringLinkedList {
private Node first = new Node();
private Node last = new Node();
public StringLinkedList() {
first.next = last;
last.prev = first;
}
public void printAll() {
Node currentElement = first.next;
while ((currentElement) != null) {
System.out.println(currentElement.value);
currentElement = currentElement.next;
}
}
public void add(String value) {
Node node = new Node();
node.value = value;
Node lastNode = last.prev;
lastNode.next = node;
node.prev = lastNode;
last.prev = node;
}
public static class Node {
private Node prev;
private String value;
private Node next;
}
}
public class Solution {
public static void main(String[] args) {
StringLinkedList stringLinkedList = new StringLinkedList();
stringLinkedList.add("1");
stringLinkedList.add("2");
stringLinkedList.add("3");
stringLinkedList.add("4");
stringLinkedList.add("5");
stringLinkedList.add("6");
stringLinkedList.add("7");
stringLinkedList.add("8");
stringLinkedList.add("9");
stringLinkedList.printAll();
}
}