java 实现栈,java实现
分享于 点击 5468 次 点评:236
java 实现栈,java实现
Java 已为我们实现了栈,先用Java 自己自带的Stack类。
package sort;
import java.util.Stack;
public class StackDemo_1 {
public static void main(String[] args) {
Stack<String> stack = new Stack<String>();
for (int i=0; i<10; i++) {
stack.push("" + i);
}
System.out.println(stack.size());
int length = stack.size();
for (int i=0; i<length; i++) {
System.out.println(stack.size() + ": " + stack.pop());
}
}
}
现在自己用数组来实现:
package sort;
/**
* @author Brook Lieu
* @version v1.0 2014-9-29
*/
public class StackDemo_1 {
/**
* 测试
* @param args
*/
public static void main(String[] args) {
Stack_1<String> stack_1 = new Stack_1<String>();
for (int i=0; i<10; i++) {
stack_1.push("" + i);
}
int stackSize = stack_1.getStackSize();
System.out.println("stack Size is " + stackSize);
for (int i=0; i<stackSize; i++) {
System.out.println(i + ": " + stack_1.pop());
}
stack_1.pop();
}
}
package sort;
import java.util.Arrays;
public class Stack_1<T> {
T[] objectDatas;
int top = -1;
int capsualSize = 10;
int size;
@SuppressWarnings("unchecked")
public Stack_1() {
objectDatas = (T[]) new Object[capsualSize];
}
// 插入
public void push(T t) {
mesureSize();
objectDatas[++top] = t;
}
public T pop() {
if (!isEmpty()) {
return objectDatas[top--];
} else {
throw new RuntimeException("栈已为空,不能再取值");
}
}
public boolean isEmpty() {
return top == -1;
}
public int getStackSize() {
return top + 1;
}
/**
* 确保栈空间够用
*/
private void mesureSize() {
if (top >= capsualSize-1) {
capsualSize = 2 * capsualSize;
@SuppressWarnings("unchecked")
T[] tempT = (T[]) new Object[capsualSize];
tempT = Arrays.copyOfRange(objectDatas, 0, top);
objectDatas = tempT;
}
}
}
输出结果为:
Exception in thread "main" stack Size is 10
0: 9
1: 8
2: 7
3: 6
4: 5
5: 4
6: 3
7: 2
8: 1
9: 0
java.lang.RuntimeException: 栈已为空,不能再取值
at sort.Stack_1.pop(Stack_1.java:26)
at sort.StackDemo_1.main(StackDemo_1.java:20)
相关文章
- 暂无相关文章
用户点评