因此,对于我的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
答案 0 :(得分:0)
首先,您可以通过在lastNode
类中添加ElementList
字段来避免使用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;
}
}
}
目前它仍然是单链接列表,但您可以在previousElement
类中添加Element
字段,并稍微更改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;
}
}