简体   繁体   中英

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. 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.

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. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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