栈可基于数组和链表来实现,基于数组的栈被称为顺序栈,栈的容量指定初始大小之后不可扩容,扩容需要传新建新数组,将原数组copy过来,
基于链表实现的栈成为链式栈,容量理论上无上限,以下分别实现
顺序栈
public class ArrayStack {
int[] stack;
public int top;
public ArrayStack(int size) {
this.stack = new int[size];
}
public boolean push(int val) {
if(top >= stack.length) {
return false;
}
stack[top++] = val;
return true;
}
public int pop() {
if(top == 0) {
return throw new IndexOutOfBoundsException();
}
return stack[--top];
}
//验证
public static void main(String[] args) {
stack.push(10);
stack.push(11);
stack.push(12);
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
}
}
链式栈:这里使用的是反向生成链结构,push时从头部插入节点,pop时从头发弹出节点。下例使用了同步机制,保证在多线程环境出入栈的安全性
public class LinkedStack {
class Node{
private String value;
private Node pre;
public Node(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
// 记录栈的长度
public int length;
// 顶部栈针
private Node top;
public boolean push(String value) {
synchronized (this) {
if (top == null) {
Node node = new Node(value);
top = node;
incrLength();
return true;
}
Node t = new Node(value);
t.pre = top;
top = t;
incrLength();
}
return true;
}
public String pop() {
if(top == null) {
return null;
}
String result = null;
synchronized (this) {
Node returnNode = top;
top = top.pre;
decLength();
result = returnNode.getValue();
}
return result;
}
private synchronized void incrLength() {
length++;
}
private synchronized void decLength() {
length--;
}
public static void main(String[] args) throws InterruptedException {
LinkedStack stack = new LinkedStack();
stack.push("a");
stack.push("b");
stack.push("c");
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.pop());
System.out.println(stack.length);
}
}