java - Stack Array is Printing Elements that have already been Popped -
after pushing , popping elements in stack array implementation, stack array printed out. when utilize next print method, prints out array elements, including ones should have been popped (and should hence gone). why this? normal, or wrong code?
if utilize isempty()
method, recognizes empty, when printing stack, prints of elements if have never been popped. stack empty , realizes it, why won't print empty stack or throw exception?
this print method in stack array class.
public void print() { (string string : array) { if (string != null) { system.out.println(string); } } }
other method there isn't out of ordinary, if help can post pop()
, push()
methods too. main thing bothering me after elements have been popped it's still not empty see left in stack array. rather printing left, though, prints everything. how can print stack array without elements have been popped?
well, if stack backed array, shouldn't print entire array when printing content of stack (since array has fixed length, , printing print fixed number of elements, regardless of current content of stack).
you must have indices tell elements of array in utilize stack. if end of stack (the first element entered) first element of array (0 indexed), must have index pointing head of stack, pop elements. in case, print method should :
public void print() { (int i=0;i<head;i++) { system.out.println(array[i]); } }
this assuming head == 0 when stack empty.
java arrays stack
No comments:
Post a Comment