使用堆栈接口定义,什么字符串在堆栈顶部,什么字符串在底部?
我知道.push方法只是将选定的项目添加到堆栈的顶部,但是我遇到的麻烦是当push方法中有pop方法或push方法中有peek方法时。
我在表示String name = stringStack.pop();的那行上也需要帮助。
public interface StackInterface<T>
{
// Adds a new entry to the top of the stack
public void push( T newEntry );
// Removes and returns the stack’s top entry
public T pop();
// Retrieves this stack’s top entry
public T peek();
}
StackInterface<String> stringStack = new MyStack<>();
stringStack.push( “Jane” );
stringStack.push( “Jess” );
stringStack.push( “Jill” );
stringStack.push( stringStack.pop());
stringStack.push( stringStack.peek());
stringStack.push( “Jim” );
String name = stringStack.pop();
stringStack.push( stringStack.peek());
我希望订单为:
TOP Jim Jim Jill Jill Jess Jane BOTTOM
在这种情况下:
stringStack.push( stringStack.pop());
您只需要记住,push
必须知道要推送的值,然后再推送该值。它怎么知道要推销什么价值?当然要评估pop()
!因此,首先弹出一个项目,然后push
知道要推送的项目,然后再推送回去。换句话说,总体上pop
内的push
对堆栈没有任何作用。
关于:
stringStack.push( stringStack.peek());
而不是弹出顶部项目然后将其推入,它只会查看顶部项目,然后将其推入堆栈。因此,总的来说,这只是“复制”最上面的项目。