【发布时间】:2019-03-16 08:03:22
【问题描述】:
我正在尝试编写此问题的代码。
假设给定一个由 n 个节点组成的链表,每个节点存储一个整数。编写一个高效的 Java 代码,打印 n 个字符串数组中链表中奇数的所有循环移位。 例如,如果列表是 1 → 2 → 15 → 14 → 23,则输出将是一个字符串数组 str,使得
str [0] = “1, 15, 2300
, str [1] = “15, 23, 1
00, and str [2] = “23, 1, 1500.
请注意,数字之间用 ‘,’,它们之间没有空格。 您需要创建一个名为 Shifts 的类,该类具有以下方法:
public static String[]
giveShifts (LinkedList<Integer> list)
。这里的list是一个维护整数的链表
我尝试调试我的代码,但无济于事。它遍历所有节点,一旦到达最后一个节点,该值为空。我不太清楚为什么。
import java.util.Arrays;
public class Shifts
{
public static String[] giveShifts(LinkedList<Integer> list)
{
String[] result = new String[list.length()];
StackInt odds = new StackInt(list.length());
Node curr = list.head;
while(curr != null)
{
if ((Integer)curr.getValue() % 2 == 0)
{
odds.push(((int)curr.getValue()));
}
curr = curr.next;
}
int[] nums = new int[list.length()];
String numsStr = "";
while(!odds.isEmpty())
{
for(int i=0; i<result.length; i++)
{
nums[i] = odds.pop();
}
numsStr = Arrays.toString(nums);
for(int j=0; j<result.length; j++)
{
result[j] = numsStr;
}
}
return result;
}
}
【问题讨论】:
-
你的缩进到处都是,让你的代码真的很难阅读。也许纠正它也会发现任何错误。
-
@GolezTrol 完成。抱歉,我是使用 stackoverflow 的新手!
标签: java nullpointerexception linked-list queue