iT邦幫忙

0

JAVA新手發問

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;
	}
}
看更多先前的討論...收起先前的討論...
從你的錯誤訊息來看,你是記憶體用量超過。
再看你的twoListAdd那段。你可能要檢查一下你的list1及list2的進去量。
如果你確定真的量沒很大的話。
或許你可以檢查一下,是否有跑成無限回圈的情況發生了。
a000114 iT邦新手 5 級 ‧ 2018-10-17 14:09:46 檢舉
是的 我的前面函式有丟到測試過是正常輸出的
所以我確定是twolistadd那邊出錯
a000114 iT邦新手 5 級 ‧ 2018-10-17 14:11:12 檢舉
可是如果我的while迴圈再跑輸出時可以執行 代表我的list1 list2 是有終點的 那為什麼twoListAdd那邊的while會變成無限迴圈呢 還煩請大大解惑 謝謝
weiclin iT邦高手 4 級 ‧ 2018-10-17 14:26:16 檢舉
因為你少了 list1 = list1.nextNode 這樣的動作
a000114 iT邦新手 5 級 ‧ 2018-10-17 14:32:27 檢舉
大神我愛你
a000114 iT邦新手 5 級 ‧ 2018-10-17 14:33:03 檢舉
十分感謝
a000114 iT邦新手 5 級 ‧ 2018-10-17 14:36:30 檢舉
另外我的while判斷式也應該改成 (list1 != null) && (list2 != null) 不然最後一個做不到
謝謝各位大神協助
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友回答

立即登入回答