[英]Doubly LinkedList Previous Instance Variable
因此,对于我的 Java 编程课程,我们了解了双向链表,并且我得到了一个对象中的 3 个节点相互指向的要点。 然而,在他给我们的实验室中,我完全不知道如何使链表中的节点指向前一个。 我见过其他程序做同样的事情,但我不确定如何将它合并到我自己的代码中。 我想过使用“previousNode 对象”,但不确定这是否是正确的方法。 所以我的问题是你将如何创建一个指向前一个节点的指针和前一个节点来指向新节点? 注意:新节点将被添加到列表的末尾。
在链表中添加元素的方法
class ElementList
{
Element firstNode;
public ElementList()
{
this.firstNode = null;
}
public void addElement( String first, String last, long number )
{
Element previousNode, newNode, currentNode;
newNode = new Element( first, last, number );
if ( this.firstNode == null) // Determine if there is a firstNode
{
this.firstNode = newNode; // Store the first node
}
else
{
currentNode = this.firstNode; // Assign temporary element to first
while ( currentNode.nextElement != null ) // Check if this is last element or header
{
currentNode = currentNode.nextElement; // Go to the next element
}
currentNode.nextElement = newNode; // Point last element of list to newNode
}
}
这是完整源代码的链接: https : //docs.google.com/document/d/18F4nKoRN5kdVcQ7IRWjrCE3hAKGD32BmRxaZTbW7CSc/edit?usp=sharing
这是整个作业的链接: https : //drive.google.com/file/d/1POEAsdNrB3wJPI0ddsbJp2HnUay5pgei/view?usp=sharing
首先,您可以通过在ElementList
类中添加lastNode
字段来避免 while 循环:
class ElementList {
Element firstNode;
Element lastNode;
public ElementList() {
this.firstNode = null;
this.lastNode = null;
}
public void addElement(String first, String last, long number) {
Element previousNode, newNode, currentNode;
newNode = new Element(first, last, number);
if (this.firstNode == null) // Determine if there is a firstNode
{
this.firstNode = newNode; // Store the first node
this.lastNode = newNode; // ... and the last node
} else {
this.lastNode.nextElement = newNode;
this.lastNode = newNode;
}
}
}
目前它仍然是一个单向链表,但您可以在Element
类中添加一个previousElement
字段,并稍微更改addElement
方法:
public void addElement(String first, String last, long number) {
Element previousNode, newNode, currentNode;
newNode = new Element(first, last, number);
if (this.firstNode == null) // Determine if there is a firstNode
{
this.firstNode = newNode; // Store the first node
this.lastNode = newNode; // ... and the last node
} else {
this.lastNode.nextElement = newNode;
newNode.previousElement = this.lastNode;
this.lastNode = newNode;
}
}
现在您可能想要编写一个删除节点的方法:
public void removeElement(Element node) {
if (node.nextElement == null) {
// node is the last node
this.lastNode = node.previousElement;
if (this.lastNode != null) {
this.lastNode.nextElement = null;
}
} else {
node.nextElement.previousElement = node.previousElement;
}
if (node.previousElement == null) {
// node is the first node
this.firstNode = node.nextElement;
if (this.firstNode != null) {
this.firstNode.previousElement = null;
}
} else {
node.previousElement.nextElement = node.nextElement;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.