使用链表实现栈比实现一个单链表要简单很多。可以只在链表头进行数据的存取。
下面给出实现:
import java.util.StringJoiner;
class LinkedStack<Z> {
private static class Node<R> {
R data;
Node<R> next;
}
private final int capacity;
private final Node<Z> head = new Node<>();
private int length = 0;
public LinkedStack(int capacity) {
this.capacity = capacity;
}
public int size() {
return length;
}
public boolean isEmpty() {
return length == 0;
}
public boolean isFull() {
return capacity == size();
}
public boolean push(Z data) {
// add ele
if (data == null || isFull()) {
return false;
}
Node<Z> h = head;
Node<Z> item = new Node<>();
item.data = data;
item.next = h.next;
h.next = item;
length++;
return true;
}
public Z pop() {
if (isEmpty()) {
return null;
}
Node<Z> h = head;
Node<Z> target = h.next;
Z data = target.data;
h.next = target.next;
target.data = null;
target.next = null;
length--;
return data;
}
private String format() {
StringBuilder sb = new StringBuilder("{ ");
Node<Z> h = head;
while (h.next != null) {
h = h.next;
sb.append(h.data).append(", ");
}
int last = sb.lastIndexOf(", ");
if (last != -1) {
sb.delete(last, last + 2);
}
sb.append(" }");
return sb.toString().replaceAll(" {2}", "");
}
public void clear() {
while (!isEmpty()) {
pop();
}
}
@Override
public String toString() {
return new StringJoiner(", ",
LinkedStack.class.getSimpleName() + "[",
"]")
.add("data=" + format())
.add("size=" + size())
.add("capacity=" + capacity)
.toString();
}
public static void main(String[] args) {
LinkedStack<Integer> stack = new LinkedStack<>(4);
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);
}
}
}
关于单链表的实现可以看之前的文章:java 单链表实现 及 反转单链表.
可以看一下输出效果:
push: true | LinkedStack[data={ 1 }, size=1, capacity=4]
push: true | LinkedStack[data={ 2, 1 }, size=2, capacity=4]
push: true | LinkedStack[data={ 3, 2, 1 }, size=3, capacity=4]
push: true | LinkedStack[data={ 4, 3, 2, 1 }, size=4, capacity=4]
push: false | LinkedStack[data={ 4, 3, 2, 1 }, size=4, capacity=4]
clear? LinkedStack[data={}, size=0, capacity=4]
push: true | LinkedStack[data={ 11 }, size=1, capacity=4]
push: true | LinkedStack[data={ 12, 11 }, size=2, capacity=4]
push: true | LinkedStack[data={ 13, 12, 11 }, size=3, capacity=4]
push: true | LinkedStack[data={ 14, 13, 12, 11 }, size=4, capacity=4]
push: false | LinkedStack[data={ 14, 13, 12, 11 }, size=4, capacity=4]
pop: 14 | stack=LinkedStack[data={ 13, 12, 11 }, size=3, capacity=4]
pop: 13 | stack=LinkedStack[data={ 12, 11 }, size=2, capacity=4]
pop: 12 | stack=LinkedStack[data={ 11 }, size=1, capacity=4]
pop: 11 | stack=LinkedStack[data={}, size=0, capacity=4]