我目前正在创建一个双向链表,但我正在努力这样做,因为构造函数需要前一个元素和下一个元素。然而,检查列表只会产生两个空元素,头部和尾部。节点的构造函数是
public Node(Node prev, Node next, String link) {
this.prev = prev;
this.next = next;
this.link = link;
}
我拥有的空列表的构造函数是
public DoublyLinkedList() {
head = tail = null;
}
我添加元素的代码是
public void addElement(String link) {
Node n = new Node(tail.prev, tail, link);
if (head == null) {
head = n;
head.next = n;
}
tail.prev = n;
tail = n;
}
我知道我导致 null 的原因是因为当我将它传递给构造函数时 tail == null 。但是,我不知道如何在创建新节点之前更新 tail 的值。我尝试构建空列表
public DoublyLinkedList() {
head = tail = null;
head.prev = null;
head.next = tail;
tail.next = null;
tail.prev = head;
}
但这也没有显示添加的元素。
addElement
如果是这种情况,我将假设将一个元素添加到列表的末尾,试试这个
Node n = new Node(tail, null, link); // The new tail
if (head == null) {
head = n;
tail = n;
}else{
tail.next = n;
tail = n;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句