printing stack without popping elements java -


for task have write method prints stack, part easy

public void print(stack s) {    while(!isempty())    {       system.out.println(s.peek());       s.pop();    }  } 

the problem after printed stack, task print bottom element on stack, isn't there more cause used s.pop() in print method. code printing bottom element.

public void bottom(stack s) {   if(isempty())    {      system.out.println("stack empty");    }   else    {      system.out.println(stackarray[0]);    } } 

my question is: how should modifie print method don't have pop elements stack? or there way make stack still holds elements after using print method?

as resquested stack we're using in our classes(most of in dutch):

public class mystack {     protected object[ ] stackarray;     protected int top;     private int grootte;     private static final int default_grootte = 10;      public mystack( )     {         grootte = default_grootte;         stackarray = new object[grootte];         top = 0;     }      public boolean isempty( )     {         if (top == 0)                 return true;             else                  return false;     }      public void push(object e)     {         if (top == grootte)             allocatemore( );         stackarray[top] = e;         top++;     }      public object pop( )     {             if(isempty( ))             {                 system.out.println("stack leeg : er kan geen element van de stack afgehaald worden.");                 return null;             }                     top--;                     return stackarray[top];  }     public object peek( )     {             if(isempty( ))             {                 system.out.println("stack leeg : er kan geen topelement van de stack getoond worden.");                 return null;             }                     return stackarray[top-1];     }      public int size( )     {         return top;     }      private void allocatemore( )     {         object[ ] original = stackarray;         grootte = grootte * 2;         stackarray = new object[ grootte];         for(int = 0; < grootte/2; i++)         {             stackarray[i] = original[i];     }     }  } 

since rep isn't high enough answer own question quick edit

i think i've found other way print stack using this

public void print(stack s) {  for(int =top-1; i>=0;i--)    system.out.println(stackarray[i]); } 

it isn't best way it, it's working :p

if use built-in java.util.stack type, derives vector, can use getelement(int) read elements @ stack depth.

if own code, have add method same.

alternatively, can pop elements stack or list type , rebuild stack after printing inefficient , teacher frown such solution.


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -