我有以下课程
class ListNode
{
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
我的任务是编写一个方法:
- 作为
int[]参数。 - 反转数组。
- 返回
ListNode数组中当前元素的值,.next新创建的 ListNode 与数组中的相应值,依此类推。
给定new int[]{0, 8, 7};I expect to get a ListNodewhere value is 7 的输入,.next是一个值为 8 的新节点,最后.next.next是一个值为 0 的新节点。
我编写了以下方法来完成这种行为
public static ListNode reverseAndLinkToListNode(int [] arrayToReverse)
{
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("js");
int finalDigitsArrayLength = arrayToReverse.length;
ListNode finalNode = new ListNode();
if (finalDigitsArrayLength > 0)
{
finalNode.val = arrayToReverse[finalDigitsArrayLength - 1];
int j = 1;
for (int i = finalDigitsArrayLength - 2; i >= 0; i--)
{
try
{
// create a new list node
ListNode newlyCreatedNode = new ListNode(arrayToReverse[i]);
// calculate how many 'nexts' I need
String codeToExecute = returnNumberOfNexts(j);
// set the next field with the list node I just created
engine.eval(codeToExecute);
}
catch (Exception e)
{
System.out.println(e);
}
j++;
}
}
return finalNode;
}
public static String returnNumberOfNexts(int nextCounter)
{
String finalDotNextString = "finalNode";
if (nextCounter > 0)
{
for (int i = 0; i < nextCounter; i++)
{
finalDotNextString += ".next";
}
}
finalDotNextString += " = newlyCreatedNode;";
return finalDotNextString;
}
上面的解决方案返回要执行的正确代码,但是在执行时,我得到:
javax.script.ScriptException: ReferenceError: "finalNode" is not defined in <eval> at line number 1
如何在引擎中定义finalNode和变量?newlyCreatedNode