Java 底层是Stack实现继承了vector,Stack类主要调用了父类的方法,本身方法也不多,可以看看它的源码
public
class Stack<E> extends Vector<E> {
/**
* Creates an empty Stack.
*/
public Stack() {
}
/**
* Pushes an item onto the top of this stack. This has exactly
* the same effect as:
* <blockquote><pre>
* addElement(item)</pre></blockquote>
*
* @param item the item to be pushed onto this stack.
* @return the {@code item} argument.
* @see java.util.Vector#addElement
*/
public E push(E item) {
addElement(item);
return item;
}
/**
* Removes the object at the top of this stack and returns that
* object as the value of this function.
*
* @return The object at the top of this stack (the last item
* of the {@code Vector} object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E pop() {
E obj;
int len = size();
obj = peek();
removeElementAt(len - 1);
return obj;
}
/**
* Looks at the object at the top of this stack without removing it
* from the stack.
*
* @return the object at the top of this stack (the last item
* of the {@code Vector} object).
* @throws EmptyStackException if this stack is empty.
*/
public synchronized E peek() {
int len = size();
if (len == 0)
throw new EmptyStackException();
return elementAt(len - 1);
}
/**
* Tests if this stack is empty.
*
* @return {@code true} if and only if this stack contains
* no items; {@code false} otherwise.
*/
public boolean empty() {
return size() == 0;
}
/**
* Returns the 1-based position where an object is on this stack.
* If the object {@code o} occurs as an item in this stack, this
* method returns the distance from the top of the stack of the
* occurrence nearest the top of the stack; the topmost item on the
* stack is considered to be at distance {@code 1}. The {@code equals}
* method is used to compare {@code o} to the
* items in this stack.
*
* @param o the desired object.
* @return the 1-based position from the top of the stack where
* the object is located; the return value {@code -1}
* indicates that the object is not on the stack.
*/
public synchronized int search(Object o) {
int i = lastIndexOf(o);
if (i >= 0) {
return size() - i;
}
return -1;
}
}
可以看出,Stack拥有的方法有pop()和push(),删除元素和添加元素,栈数据结构大家都知道,先进后出,如直接走vector的删除和添加也可以达到同样的效果,进入到元素删减的方法里面还是走的就是vector的方法。下面先来说说push主要是添加元素,因为底层还是数据实现,stack的添加元素按照顺序添加就可以了,不过pop()出的时候是从数组尾部删除,这也就是为什么栈是先进后出的原因所在
使用stack可以实现深度查询树
Stack<TreeNode> myStack=new Stack<>();
myStack.add(head);
while(!myStack.isEmpty()) {
TreeNode node=myStack.pop(); //弹出栈顶元素
System.out.print(node.data+" ");
if(node.rightNode!=null) {
myStack.push(node.rightNode); //深度优先遍历,先遍历左边,后遍历右边,栈先进后出
}
if(node.leftNode!=null) {
myStack.push(node.leftNode);
}
}