实现 - 栈
栈的实现比队列容易。动态数组足以实现堆栈结构。
class MyStack {
private List<Integer> data; // store elements
public MyStack() {
data = new ArrayList<>();
}
/** Insert an element into the stack. */
public void push(int x) {
data.add(x);
}
/** Checks whether the queue is empty or not. */
public boolean isEmpty() {
return data.isEmpty();
}
/** Get the top item from the queue. */
public int top() {
return data.get(data.size() - 1);
}
/** Delete an element from the queue. Return true if the operation is successful. */
public Integer pop() {
if (isEmpty()) {
return null;
}
Integer pop = data.get(data.size() - 1);
data.remove(data.size() - 1);
return pop;
}
public static void main(String[] args) {
MyStack s = new MyStack();
s.push(1);
s.push(2);
s.push(3);
for (int i = 0; i < 4; ++i) {
System.out.println(s.pop());
}
}
}
3
2
1
null
总结
栈是一种先进后出(LIFO)的数据结构。与队列类似,总是在堆栈的末尾添加一个新元素。但是,删除操作,退栈 pop ,将始终删除队列中相对于它的最后一个元素。