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;
}
}
这是一个司机代码的一部分,我的老师给我,以经受住堆叠。我理解堆栈的每个部分所做的事情,只是不了解如何基于这段代码实现堆栈。我需要帮助,主要是peek方法,但如果你看到其他问题,请告诉我。我很感谢你的帮助。
发布于 2017-04-16 18:56:07
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);
}
https://stackoverflow.com/questions/43440858
复制相似问题