Java数据结构:栈的实现
上一篇 /
下一篇 2012-05-18 08:58:42
/ 个人分类:Java
栈是Java语言中最重要的数据结构之一,它的实现,至少应该包括以下几个方法:3rrq(Z@0 1、pop() 出栈操作,弹出栈顶元素。
G'i|D6xzWpaW0F&F_)n q~w0 2、push(E e) 入栈操作51Testing软件测试网"bP7C0z+u9b+s6e
i)]
LF E'Hi2w0 3、peek() 查看栈顶元素
Jr[#MEy5b[%sl0(oH9za
G0 4、isEmpty() 栈是否为空
YT,]"XyE+BqqD0*t;GC,FA:|@0 另外,实现一个栈,还应该考虑到几个问题:
*c1|wG2YQ]b9a051Testing软件测试网OSw
`R(}g6g 1、栈的初始大小以及栈满以后如何新增栈空间
$bP:h8i:t(N S6Iq0]w p051Testing软件测试网v}N `9lL;Z)_ K 2、对栈进行更新时需要进行同步
KH*x7~1?%x;b8M6\6c0q t])]FA!] }+j7w0 简单示例,使用数组实现栈,代码如下:
/l$EpC6\(jZP+n0- <pre name="code" class="java">public class Stack<E> {
- 51Testing软件测试网.nO
|G}b,F:\
-
- private Object[] stack;
8@1k${m[/JD0-
- private static final int INIT_SIZE = 2;
- 51Testing软件测试网5@M*]%Y6q7L%o
-
- private int index;
.G#Tj7L*y8]e2CF0m8R0- public Stack() {
- stack = new Object[INIT_SIZE];
- index = -1;
- }
- 51Testing软件测试网EUN gAR:K
{3V
-
-
-
-
-
-
- public Stack(int initSize) {
- if (initSize < 0) {
- throw new IllegalArgumentException();
- }
- stack = new Object[initSize];
- index = -1;
- }
3i}!|
d.x^&j
_0-
-
-
-
-
- public synchronized E pop() {
- if (!isEmpty()) {
- E temp = peek();
- stack[index--] = null;
- return temp;
- }
- return null;
- }
- 51Testing软件测试网 Pj}1H'vh/o!H
-
-
-
-
-
-
- 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;
- }
4u
|)l2F
w/kK
?/g'O{0-
-
-
-
-
- public E peek() {
- if (!isEmpty()) {
- return (E) stack[index];
- }
- return null;
- }
x\dAhaJS#b0-
-
-
-
-
- public boolean isEmpty() {
- return index == -1;
- }
- 51Testing软件测试网c#um9Yc
lg
-
-
-
-
-
- public boolean isFull() {
- return index >= stack.length - 1;
- }
- }
|
HW W9d1K0 最后说明,Java中实现了栈(java.util.Stack)的数据结构,它是通过继承Vector类实现的,一般情况下我们直接拿来用就行了。51Testing软件测试网 PE!L+z)q;J#~8s7a;I~.U
收藏
举报
TAG: