栈是一种后进先出的数据结构,只有一个方向可以进行数据的存取。基于此,可以很容易的使用数组进行实现。
下面给出具体实现:
import java.util.StringJoiner;
class ArrayStack<Z> {
private final int capacity;
private final Object[] array;
private int topPos = -1;
public ArrayStack(int capacity) {
this.capacity = capacity;
array = new Object[capacity];
}
public int size() {
return topPos + 1;
}
public boolean isFull() {
return size() == capacity;
}
public boolean isEmpty() {
return size() == 0;
}
public boolean push(Z data) {
if (isFull() || data == null) {
return false;
}
array[++topPos] = data;
return true;
}
public Z pop() {
if (isEmpty()) {
return null;
}
return (Z) array[topPos--];
}
public void clear() {
while (!isEmpty()) {
pop();
}
}
private String format() {
StringBuilder sb = new StringBuilder("{ ");
for (int i = topPos; i >= 0; --i) {
sb.append(array[i]).append(", ");
}
int last = sb.lastIndexOf(", ");
if (last != -1) {
sb.delete(last, last + 2);
}
sb.append(" }");
return sb.toString().replaceAll(" {2}", "");
}
@Override
public String toString() {
return new StringJoiner(", ",
ArrayStack.class.getSimpleName() + "[", "]")
.add("data=" + format())
.add("size=" + size())
.add("capacity=" + capacity)
.toString();
}
public static void main(String[] args) {
ArrayStack<Integer> stack = new ArrayStack<>(3);
System.out.println(stack);
for (int i = 0; i < 5; ++i) {
boolean push = stack.push(i + 1);
System.out.printf("push: %s | %s\n", push, stack);
}
stack.clear();
System.out.println("clear? " + stack);
for (int i = 0; i < 5; ++i) {
boolean push = stack.push(i + 11);
System.out.printf("push: %s | %s\n", push, stack);
}
while (!stack.isEmpty()) {
Integer pop = stack.pop();
System.out.printf("pop: %s | stack=%s\n", pop, stack);
}
}
}
代码量很少。甚至不需要专门的封装,直接使用数组即可完成。
可以看一下输出的效果:
ArrayStack[data={}, size=0, capacity=3]
push: true | ArrayStack[data={ 1 }, size=1, capacity=3]
push: true | ArrayStack[data={ 2, 1 }, size=2, capacity=3]
push: true | ArrayStack[data={ 3, 2, 1 }, size=3, capacity=3]
push: false | ArrayStack[data={ 3, 2, 1 }, size=3, capacity=3]
push: false | ArrayStack[data={ 3, 2, 1 }, size=3, capacity=3]
clear? ArrayStack[data={}, size=0, capacity=3]
push: true | ArrayStack[data={ 11 }, size=1, capacity=3]
push: true | ArrayStack[data={ 12, 11 }, size=2, capacity=3]
push: true | ArrayStack[data={ 13, 12, 11 }, size=3, capacity=3]
push: false | ArrayStack[data={ 13, 12, 11 }, size=3, capacity=3]
push: false | ArrayStack[data={ 13, 12, 11 }, size=3, capacity=3]
pop: 13 | stack=ArrayStack[data={ 12, 11 }, size=2, capacity=3]
pop: 12 | stack=ArrayStack[data={ 11 }, size=1, capacity=3]
pop: 11 | stack=ArrayStack[data={}, size=0, capacity=3]