Search code examples
javatextpad

Get call in stack Java


   public void push(E e)
  {
    list.add(e);
   }
public E pop()
{
    list.remove(list.size()-1);
}
public E peek()
{

}

public boolean empty()
{
   if ( list.size()== 0)
   {
       return false;
   }
   else
   {
       return true;
   }
}

This is part of a driver code my teacher gave me in order to under stand the stack. I understand what each part of the stack does, I am just not understanding how to implement the stack based on this code. I need help with the peek method mainly, but if you see other issues please let me know. I would appreciate the help.


Solution

  • public E peek(){
      if(empty()) return null;
    
      int top = list.size()-1;
      return list.get(top);
    }
    

    AND empty method can be simplifized to:

    public boolean empty(){
      return  list.size() == 0;
    }
    

    OR

    public boolean empty(){
      return  list.isEmpty();
    }
    

    AND pop method should throws NoSuchElementException when stack is empty.

    public E pop(){
      if(empty()) throw new NoSuchElementException();
    
      int top = list.size()-1;
      return list.remove(top);
    }