如何在Java中设置循环链表中的下一个值?
这就是我到目前为止所做的:如何在Java中设置循环链表中的下一个值?,java,list,next,Java,List,Next,这就是我到目前为止所做的: public void insert(int position, ValueNode value) { if (position == 1) { this.nextInRow = value; } ValueNode current = this.getFirst(); if (position > 1) { current.setNext(current.next); } value.setNextInRow(cur
public void insert(int position, ValueNode value) {
if (position == 1) {
this.nextInRow = value;
}
ValueNode current = this.getFirst();
if (position > 1) {
current.setNext(current.next);
}
value.setNextInRow(current.getNext());
}
正在使用第一条if语句正确设置headnode。在这个列表中,我们已经知道了位置,所以我认为我们不需要while循环,因为我们知道将新节点放置在何处
我创建了一个名为current的临时节点来保存下一个节点指针,但现在它将指针设置为null。我的问题是我不知道下一个节点指针指向哪里。任何帮助都将不胜感激 区分使用值创建节点和设置下一个节点操作 您的数据结构可以如下所示:
class Node {
int val;
Node next;
Node previous;
//setters and getters and constructors
}
1) 对于所有新值,都应该有一个节点
Node createNode(int val) {
Node newNode = new Node(val);
newNode.next = null;
newNode.previous = null;
return newNode;
}
2) 找到从根开始的新节点,或保留当前节点并将其设置为下一个
currentNode.setNext(Node newNode);
//iterate the currenNode with newNode
currentNode = newNode;
...
// implement the setNext and mark current as previous for newNode
void setNextNode(Node newNode) {
this.next = newNode;
newNode.setPrevious(this);
}
除非您有一个包含节点的数组,否则您将需要while循环来找到正确的位置。但是这些代码不足以帮助您-我们不知道
getFirst
的作用是什么,列表是单链接还是双链接。您需要添加ValueNode
和至少setNext()
以及此代码中引用的任何方法和变量或它所依赖的任何代码。getFirst只返回列表中的第一个节点。。。这是一个SLL。。但是最后一个节点应该指向第一个节点,使其循环..值得注意的是,insert方法位于一个位置,因此我们知道将新节点放置在何处。。。我想我的问题是我不知道如何存储下一个值。。例如,如果我插入node2,但我必须让node2指向node3。。我如何知道node3在哪里..这就是为什么首先创建val的节点并将此节点设置为上一个节点的下一个节点。这将把它们连接在一起。