我需要递归地编写getNodeAt()
方法。
这是原始方法:
private Node getNodeAt(int givenPosition) {
Node currentNode=firstNode;
for (int i =0; i < givenPosition; i++)
currentNode=currentNode.next;
return currentNode;
}
这是我的尝试:
private Node getNodeAt(int givenPosition) {
Node currentNode;
if (givenPosition == 0) {
return currentNode = firstNode;
} else {
return getNodeAt(givenPosition - 1);
}
}
最佳答案
您必须在每个递归调用中将一些 Node
引用推进到下一个节点,这意味着您需要一个额外的参数:
private Node getNodeAt(Node currentNode, int givenPosition) {
if (givenPosition == 0){
return currentNode;
}else {
return getNodeAt(currentNode.next, givenPosition - 1);
}
}
对该方法的初始调用是
Node node = getNodeAt (firstNode, someIndex);
或者您可以创建一个包含初始调用的附加方法:
public Node getNodeAt(int givenPosition) {
return getNodeAt (firstNode, givenPosition);
}
关于java - 递归获取NodeAt java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34474879/