简体   繁体   English

堆栈数组是打印已弹出的元素

[英]Stack Array is Printing Elements that have already been Popped

After pushing and popping elements in a stack array implementation, I would like for the stack array to be printed out. 在堆栈数组实现中推送和弹出元素之后,我希望将堆栈数组打印出来。 When I use the following print method, it prints out the array with all the elements, including the ones that should have been popped (and should therefore be gone). 当我使用以下打印方法时,它会打印出包含所有元素的数组,包括应该已经弹出(因此应该消失)的元素。 Why does it do this? 为什么这样做呢? Is this normal, or is something wrong with my code? 这是正常现象,还是我的代码有问题?

If I use the isEmpty() method, it recognizes that it is empty, but when printing the stack, it prints all of the elements as if they have never been popped. 如果我使用isEmpty()方法,它将识别为空,但是在打印堆栈时,它将打印所有元素,就好像它们从未弹出一样。 The stack is empty and it realizes it, so why won't it print an empty stack or throw an exception? 堆栈是空的,并且意识到了,为什么不打印一个空堆栈或抛出异常?

This is the print method in the stack array class. 这是堆栈数组类中的print方法。

public void print()
{
  for (String string : array)
   {
     if (string != null)
     {
       System.out.println(string);
     }
   }
}

Other than this method there really isn't anything out of the ordinary, but if it would help I can post the pop() and push() methods too. 除了此方法外,实际上没有任何异常,但是如果有帮助,我也可以发布pop()push()方法。 The main thing that is bothering me is that after elements have been popped but it's still not empty I would like to see what is left in the stack array. 困扰我的主要事情是,在弹出元素之后,但是它仍然不是空的,我想看看堆栈数组中还剩下什么。 Rather than printing just what is left, though, it prints everything. 但是,它不打印仅剩的东西,而是打印所有内容。 How can I print the stack array without the elements that have already been popped? 如何在没有弹出元素的情况下打印堆栈数组?

Well, if your stack is backed by an array, you shouldn't print that entire array when printing the content of the stack (since that array has a fixed length, and printing it would always print a fixed number of elements, regardless of the current content of the Stack). 好吧,如果您的堆栈由数组支持,则在打印堆栈的内容时不应打印整个数组(因为该数组的长度固定,并且打印该数组将始终打印固定数量的元素,无论堆栈的当前内容)。

You must have indices that tell you which elements of that array are in use by that stack. 您必须具有索引,以告诉您该堆栈正在使用该数组的哪些元素。 If the end of the stack (the first element entered) is the first element of the array (0 indexed), you must have some index pointing to the head of the stack, from which you pop elements. 如果堆栈的末尾(输入的第一个元素)是数组的第一个元素(索引为0),则必须具有指向堆栈头的索引,然后从中弹出元素。 In that case, your print method should look like this : 在这种情况下,您的打印方法应如下所示:

public void print()
{
  for (int i=0;i<head;i++)
   {
       System.out.println(array[i]);
   }
}

This is assuming that head == 0 when the stack is empty. 假设堆栈为空时,head == 0。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM