Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Lab33.twoListAdd(Lab33.java:64)
at Lab33.main(Lab33.java:18)
他說我的堆積超出 可是我不太確定 因為我並沒有設很多的變數
我的程式是想加總兩個鏈結串列內的值
還請大大們幫我看看 是哪邊出錯 謝謝
import java.io.*;
import java.util.*;
class ListNode {
int value;
ListNode nextNode = null;
public ListNode(int value) {
this.value = value;
}
}
public class Lab33 {
public static void main(String[] args) throws IOException {
Scanner input = new Scanner(System.in);
ListNode linkedList1 = creatLinkedList();
ListNode linkedList2 = creatLinkedList();
ListNode linkedListSum = twoListAdd(linkedList1, linkedList2);
while(linkedListSum != null) {
System.out.print(linkedListSum.value);
linkedListSum = linkedListSum.nextNode;
}
}
public static ListNode creatLinkedList() {
Scanner input = new Scanner(System.in);
ListNode cPtr = null;
ListNode fPtr = null;
System.out.print("Input the LinkedList's length :");
int length = input.nextInt();
int value;
for(int i = 0; i < length; i++) {
System.out.printf("Input the %d element's value :", i);
value = input.nextInt();
ListNode t;
if(i == 0) {
t = new ListNode(value);
cPtr = t;
fPtr = t;
}else{
t = new ListNode(value);
cPtr.nextNode = t;
cPtr = t;
}
}
return fPtr;
}
public static ListNode twoListAdd(ListNode list1, ListNode list2) {
Scanner input = new Scanner(System.in);
ListNode listSum = null;
int count = 0;
ListNode cPtr = null;
ListNode fPtr = null;
while((list1.nextNode != null) && (list2.nextNode != null)) {
if(count == 0) {
listSum = new ListNode(list1.value + list2.value);
cPtr = listSum;
fPtr = listSum;
}else {
listSum = new ListNode(list1.value + list2.value);
cPtr.nextNode = listSum;
cPtr = listSum;
}
count++;
}
return fPtr;
}
}