栈(stack)是一种逻辑数据结构,代表的是先进后出的区域.就比如栈是一个杯子(形状为圆形),杯口直径为10cm,然后这个数据就是略小与杯口的饼干形状与杯口相同,然后饼干放进去后每一次只能那一块,这个时候就只能拿到最上面也就是最后放进去的那块.
用链表自己实现一个栈
public class MyStack<E> {
private Node<E> node;
public MyStack() {
}
public E push(E item) {
if (node == null) {
this.node = new Node<>(item, null, null);
} else {
this.node = new Node<>(item, node, null);
// Node previous = node.previous;
// previous.next=node;
}
return item;
}
public synchronized E pop() {
E obj = node.val;
Node previous = node.previous;
if (previous != null) {
previous.next = null;
}
this.node = previous;
return obj;
}
public synchronized E peek() {
if (node == null)
throw new EmptyStackException();
E obj = node.val;
return obj;
}
}
用数组自己实现一个栈
public class MyArrayStack<E> {
private Object[] array;
private int index;
public MyArrayStack(int size) {
this.array =new Object[size];
}
public E push(E item) {
if (index==array.length)
throw new ArrayIndexOutOfBoundsException();
array[index]=item;
index++;
return item;
}
public synchronized E pop() {
if ( array[0] == null)
throw new EmptyStackException();
E obj = (E) array[index-1];
array[index-1]=null;
index--;
return obj;
}
public synchronized E peek() {
if ( array[0] == null)
throw new EmptyStackException();
E obj = (E) array[index-1];
return obj;
}
}
这里是用固定大小的数组实现的,如果要用动态数组的话,可以换成ArrayList替换array.