下面的代码是实现单链接列表(从一个leetcode问题)。在本例中,我希望显示链接列表中的所有元素,例如,1、2、3、4。
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at java.util.Arrays.copyOf(Unknown Source)
at java.lang.AbstractStringBuilder.expandCapacity(Unknown Source)
at java.lang.AbstractStringBuilder.ensureCapacityInternal(Unknown Source)
at java.lang.AbstractStringBuilder.append(Unknown Source)
at java.lang.StringBuffer.append(Unknown Source)
at com.linkedlist.ch4.ListNode.display(leetcode_linkedlist.java:33)
at com.linkedlist.ch4.leetcode_linkedlist.main(leetcode_linkedlist.java:51)我猜测的一个问题是,每当调用display()方法时,都不会创建对象"this“。有解决办法吗?我不希望这个方法是一个无参数的方法。谢谢。
package com.linkedlist.ch4;
//Definition for singly-linked list.
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
public String toString(){
return ""+val ;
}
public void display(){
StringBuffer str = new StringBuffer();
str.append("[ ");
while(true){
ListNode start = this;
String val = start.val+"";
str = str.append(val);
start = start.next;
if(start == null){
str.append(" ]");
break;
}
str = str.append(", ");
}
System.out.println(str.toString());
}
}
public class leetcode_linkedlist {
public static void main(String[] args){
ListNode node1 = new ListNode(1);
ListNode node2 = new ListNode(2);
ListNode node3 = new ListNode(3);
ListNode node4 = new ListNode(4);
node1.next = node2;
node2.next = node3;
node3.next = node4;
node1.display();
System.out.println("------------");
System.out.println("------------");
deleteNode(node1);
node1.display();
}
public static void deleteNode(ListNode node) {
if(node == null) return;
node.val = node.next.val;
node.next = node.next.next;
}
}发布于 2015-07-16 00:10:51
您要一次又一次地将第一个节点添加到字符串中,直到内存耗尽以存储字符串:
while(true){
ListNode start = this;
// 'start' now refers to the first node (the one you called the method on)
String val = start.val+"";
str = str.append(val);
// the node 'start' is added to the current string
start = start.next;
// 'start' now refers to the second node
if(start == null){
str.append(" ]");
break;
}
// since the second node exists, don't exit the loop.
str = str.append(", ");
}您可能希望将ListNode start = this;移动到循环之前。这样,每次循环运行时,它都不会将start重置为第一个节点。
发布于 2015-07-16 00:18:23
这是一个无限循环,this总是指向第一个节点,因此ListNode start = this;总是指向同一个节点。你只需要正确地迭代
ListNode current = this;
while(current!=null){
... construct string
current = current.next
}您的猜测是:this不是创建的。完全错误,因为如果实例化对象,this引用将始终存在。
https://stackoverflow.com/questions/31443295
复制相似问题