在堆栈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;
   }
}

这是我老师给我的驾驶员代码的一部分,以便在堆栈下面。我了解堆栈的每个部分,我只是不了解如何基于此代码实现堆栈。我主要需要窥视方法的帮助,但是如果您看到其他问题,请告诉我。我会感谢您的帮助。

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

empty方法可以简化为:

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

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

pop方法应在堆栈为空时抛出NoSuchElementException

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

最新更新