打印阵列堆栈



在函数fillStackWithArray()中对数组执行某些操作,操作完成后,将数组推入堆栈并再次重复。

但当我尝试打印堆栈时,就会出现问题。它给了我错误的答案。

输出:

1 1 1 11 1 1 11 1 1 11 1 1 11 1 1 1 1

预期输出:

5 5 5 54 4 4 43 3 3 32 2 2 21 1 1 1 1

代码:

import java.util.Stack;
public class ArraysOnStack {
public static void main(String[] args) {
int sizeOfArray = 5;
Stack<int[]> stack = fillStackWithArray(5);
printStack(stack);
}
private static void printStack(Stack<int[]> stack) {
while (!stack.empty()) {
int[] arr = stack.pop();
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
}
}
private static Stack<int[]> fillStackWithArray (int size) {
Stack<int[]> stack = new Stack<>();
int[] arr = new int[size];
// Some Operation that fills Stack with Arrays.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[j] = size - i;
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr);
}
return stack;
}
}

PS:只是填充数组的操作是随机的。但我的问题与这种情况有关。

试试这个。

private static Stack<int[]> fillStackWithArray (int size) {
Stack<int[]> stack = new Stack<>();
int[] arr = new int[size];
// Some Operation that fills Stack with Arrays.
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
arr[j] = i + 1;                // changed
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr.clone());           // changed
}
return stack;
}

输出

5 5 5 5 5 
4 4 4 4 4 
3 3 3 3 3 
2 2 2 2 2 
1 1 1 1 1

您正在fillStackWithArray中的堆栈中推送相同的int[]。Java中的int数组是Object的子类,因此它是一种对象类型。在循环内创建int[]数组。

for (int i = 0; i < size; i++) {
int[] arr = new int[size];
...
}
  1. 被推送到堆栈上的int[]在循环外初始化一次。同一数组将在后续迭代中更新。您需要在循环中声明int[]数组。

  2. 分配给变量i的值应从1开始到i <= size,因为输出需要从5打印到1,并且在使用Stack时,插入顺序需要颠倒,因为推送的第一个元素将最后打印。因此,分配给arr[j]的值应该是i

for (int i = 1; i <= size; i++) {
int[] arr = new int[size];
for (int j = 0; j < size; j++) {
arr[j] = i;
}
// Pushing the array into stack on which some operation
// is performed.
stack.push(arr);
}

fillStackWithArray()函数中,您创建了一个数组arr,并且在每次迭代中更改相同的arr。要解决此问题,请为外循环的每次迭代创建一个新数组。要了解问题,请阅读有关深度复制和参考传递的内容。

最新更新