java实现栈
程序员文章站
2022-07-10 20:29:35
...
public class Test {
public static void main(String args[]) {
MyStack<Integer> stack = new MyArrayStack<Integer>();
}
public static interface MyStack<T> {
boolean isEmpty();
void clear();
int length();
boolean push(T data);
T pop();
}
public static class MyArrayStack<T> implements MyStack<T> {
private Object[] obj = new Object[16];
private int size = 0;
@Override
public boolean isEmpty() {
return (size == 0);
}
@Override
public void clear() {
for(int i = 0; i < size; i++) {
obj[i] = null;
}
size = 0;
}
@Override
public int length() {
return size;
}
@Override
public boolean push(T data) {
if(size >= obj.length) {
resize();
}
obj[size++] = data;
return true;
}
private void resize() {
Object[] temp = new Object[obj.length + 1];
for(int i = 0; i < size; i++) {
temp[i] = obj[i];
obj[i] = null;
}
obj = temp;
}
@Override
public T pop() {
if(size == 0) {
return null;
} else {
return (T) obj[--size];
}
}
}
public static class MyLinkedStack<T> implements MyStack<T> {
private Node top;
private int size;
public MyLinkedStack() {
top = null;
size = 0;
}
@Override
public boolean isEmpty() {
return (size == 0);
}
@Override
public void clear() {
top = null;
size = 0;
}
@Override
public int length() {
return size;
}
@Override
public boolean push(T data) {
Node node = new Node();
node.data = data;
node.pre = top;
top = node;
size++;
return true;
}
@Override
public T pop() {
top = top.pre;
size--;
return (T) top.data;
}
private final class Node {
private Node pre;
private T data;
}
}
}
上一篇: java栈的实现
下一篇: redis的HyperLogLog实战