java - Java 中 LinkedList 的意外行为
问题描述
我正在尝试解决需要使用的 Hacker Rank 问题,但LinkedList
我发现了一些奇怪的东西。目标是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 错误的原因。我只是添加了括号。
编辑:第一种方法也是如此。它没有向列表中添加任何内容 - 只是通过链接列表(也在那里添加括号)
推荐阅读
- git - 第 17 行 /.../bootstrap/autoload.php 中允许的 xxxx 字节内存大小已用尽(尝试分配 xxxx 字节)
- sql - 如何通过我的 Ruby on Rails 应用程序以这种方法解决高响应时间
- java - 使用杰克逊注释将列表包装到对象
- html - 错误:在此上下文中不允许元素 tbody 作为元素表的子元素。(抑制来自该子树的更多错误。)
- jquery - Firestore .get() 函数不在 JQuery 中运行 .on 点击函数
- css - Bootstrap 4 - 防止链接在导航栏上断线
- bash - 当 <
我有一个bash脚本如下
#!/usr/bin/env bash cd /Users/amar/Documents/ThesisCode/CEP_codes/mqtt-receiver sqlite3 database <<EOF SELECT sum(detection_time - generation_time)/count(*) from mobile
- scrollbar - 如何使滚动条出现在带有未定义大小的面板的窗口中?
- javascript - 为什么我的画布动画在应该加速时却变慢了?
- actionscript - GPS.ane 为我的应用程序,我不断收到错误第 55 行,第 50 列 1120:访问未定义的属性 onClickStop