首页 > 解决方案 > 我在尝试用 int 值填充堆栈数组时遇到 OutOfMemoryError

问题描述

我一直在使用堆栈研究 hanoi 递归塔,但我得到了 OutOfMemoryError: Java heap space in the hanoi function

import java.util.Scanner;
import java.util.Stack;

public class Hanoi {

    public static Stack<Integer>[] towersOfHanoi = new Stack[4];
    public static int moves;

    public static void hanoi(int n) {

        for(int i = 0; i <= 3; i++) {
            towersOfHanoi[i] = new Stack<Integer>();
        }

        for(int i = n; n > 0; i--) {
            towersOfHanoi[1].push(i);
        }

        moveDisc(n, 1, 2, 3);
    }

    public static void moveDisc(int n, int peg1, int peg2, int peg3) {

        moveDisc(n-1, peg1, peg2, peg3);
        int i = towersOfHanoi[peg1].pop();
        towersOfHanoi[peg2].push(i);
        moves++;
        moveDisc(n-1, peg3, peg1, peg2);
    }

    public static void main(String args[]) {
        Scanner in = new Scanner(System.in);

        towersOfHanoi[1] = new Stack<Integer>();
        towersOfHanoi[2] = new Stack<Integer>();
        towersOfHanoi[3] = new Stack<Integer>();

        System.out.println("Enter number of discs: ");
        int n = in.nextInt();
        in.close();

        hanoi(n);

        System.out.println(moves);


    }
}

标签: javastack

解决方案


问题出在 hanoi 函数中的第二个 for 循环中

for(int i = n; n > 0; i--) {
        towersOfHanoi[1].push(i);
    }

应该

for(int i = n; i > 0; i--) {
        towersOfHanoi[1].push(i);
    }

在您将其设置为“n> 0”之前,但 n 永远不会改变。你希望它是 'i>0'

我还应该提到,您可能会在 moveDisk 方法中获得无限递归。你应该做一个基本案例。但是,这将解决您在 hanoi 函数中遇到的 OOM 错误


推荐阅读