[英]Unexpected Behaviour of LinkedList in Java
我试图解决需要使用LinkedList
Hacker Rank问题,但发现了一些奇怪的情况。 目标是反向打印LinkedList
。
我已经尝试调试该程序,但是找不到任何错误。
在下面的第一段代码中,我只能将LinkedList
的第一个和最后一个元素放入ArrayList
。
static void reversePrint(SinglyLinkedListNode head) {
List<Integer> tempList = null;
if (head == null)
return;
else {
tempList = new ArrayList<>();
tempList.add(head.data);
while(head.next != null)
head = head.next;
tempList.add(head.data);
}
System.out.println("Size of the List -"+tempList.size());
for(int i = tempList.size()-1; i >= 0; i--)
System.out.println("Index +"+i+" "+tempList.get(i));
}
在下面的代码中,我得到了java.lang.OutOfMemoryError: Java heap space
并且我无法理解实际上是什么导致了此错误。
static void reversePrint(SinglyLinkedListNode head) {
List<Integer> tempList = null;
if (head == null)
return;
else {
tempList = new ArrayList<>();
while(head.next != null)
tempList.add(head.data);
head = head.next;
}
tempList.add(head.data);
System.out.println("Size of the List -"+tempList.size());
for(int i = tempList.size()-1; i >= 0; i--)
System.out.println("Index +"+i+" "+tempList.get(i));
}
您应该始终在代码块周围使用方括号。
static void reversePrint(SinglyLinkedListNode head) {
List tempList = null;
if (head == null)
return;
else{
tempList = new ArrayList<Integer>();
while(head.next != null) {
tempList.add(head.data);
head = head.next;
}
}
tempList.add(head.data);
System.out.println("Size of the List -"+tempList.size());
for(int i = tempList.size()-1;i>=0;i--)
System.out.println("Index +"+i+" "+tempList.get(i));
}
您的代码使得while循环仅是一条语句: tempList.add(head.data);
进度语句head = head.next;
不是循环的一部分。 因此,您的循环是无限的。 这就是为什么您收到OOM错误。 我刚刚添加了括号。
编辑:第一种方法也一样。 它没有在列表中添加任何内容-只是浏览了链接列表(也添加了括号)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.