我有一个字符数组,我试图将每个字符转换为链接到行中下一个节点的节点。问题是我一直陷入无限循环,我不知道为什么。这是我的代码:
String map = "ABBACBCCA";
char[] charArray = map.toCharArray();
ListNode head;
ListNode temp;
ListNode next;
for (int i = 0; i < charArray.length - 1; i++) {
temp = new ListNode(charArray[i]);
next = new ListNode(charArray[i+1]);
temp.next = next;
if (i == 0) {
head = temp;
}
}
ListNode 类如下所示:
class ListNode<T> {
public T data = null;
public ListNode next = null;
public ListNode(T data) {
this.data = data;
}
}
看起来它到达了 for 循环的最后一次迭代,然后陷入了无限循环。有人知道为什么吗?
最佳答案
对于开始,我认为你会想要:
next = new ListNode(charArray[i]);
成为
next = new ListNode(charArray[i+1]);
我注意到的其他事情:
for (int i = 0; i < charArray.length - 1; i++) {
temp = new ListNode(charArray[i]);
next = new ListNode(charArray[i+1]);
temp.next = next;
if (i == 0) {
head = temp;
}
}
我不认为这会产生你想要的结果。它不会给你 A->B->B->A 等等,更多的是它会给你 -> A->B,B->B 等等。不确定这是否是你想要的。
此外,我认为这应该会让你受益匪浅:
String map = "ABBACBCCA";
ListNode<Character> head = null;
ListNode<Character> newHead = null;
ListNode<Character> next = null;
char[] charArray = map.toCharArray();
head = newHead = new ListNode<Character>(charArray[0]);
for (int i = 1; i < charArray.length - 1; i++) {
next = new ListNode<Character>(charArray[i]);
newHead.next = next;
newHead = next;
}
基本上是创建和链接以及创建和链接。 (对我来说测试得很好)即将到来的丑陋!
System.out.println(head.data);
ListNode<Character> nextptr = head.next;
while (true) {
if (nextptr.next == null) {
break;
}
System.out.println(nextptr.data);
nextptr = nextptr.next;
}
关于java - 将数组转换为 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19532307/