栈是Java语言中最重要的数据结构之一,它的实现,至少应该包括以下几个方法:
1、pop() 出栈操作,弹出栈顶元素。
2、push(E e) 入栈操作
3、peek() 查看栈顶元素
4、isEmpty() 栈是否为空
另外,实现一个栈,还应该考虑到几个问题:
1、栈的初始大小以及栈满以后如何新增栈空间
2、对栈进行更新时需要进行同步
简单示例,使用数组实现栈,代码如下:
- <pre name="code" class="java">public class Stack<E> {
-
- private Object[] stack;
-
- private static final int INIT_SIZE = 2;
-
- private int index;
- public Stack() {
- stack = new Object[INIT_SIZE];
- index = -1;
- }
-
-
-
-
-
-
- public Stack(int initSize) {
- if (initSize < 0) {
- throw new IllegalArgumentException();
- }
- stack = new Object[initSize];
- index = -1;
- }
-
-
-
-
-
- public synchronized E pop() {
- if (!isEmpty()) {
- E temp = peek();
- stack[index--] = null;
- return temp;
- }
- return null;
- }
-
-
-
-
-
-
- public synchronized void push(E obj) {
- if (isFull()) {
- Object[] temp = stack;
-
- stack = new Object[2 * stack.length];
- System.arraycopy(temp, 0, stack, 0, temp.length);
- }
- stack[++index] = obj;
- }
-
-
-
-
-
- public E peek() {
- if (!isEmpty()) {
- return (E) stack[index];
- }
- return null;
- }
-
-
-
-
-
- public boolean isEmpty() {
- return index == -1;
- }
-
-
-
-
-
- public boolean isFull() {
- return index >= stack.length - 1;
- }
- }
|
最后说明,Java中实现了栈(java.util.Stack)的数据结构,它是通过继承Vector类实现的,一般情况下我们直接拿来用就行了。