栈是先进后出。其实现主要有两种,一种是基于链表的实现,一种是基于数组的实现。
基于链表的实现
import java.util.Iterator;
import java.util.NoSuchElementException;
/*
* 基于单向链表实现的栈,先进后出
*/
public class Stack<Item> implements Iterable<Item> {
private Node<Item> first; // top of stack
private int n; // size of the stack
// helper linked list class
private static class Node<Item> {
private Item item;
private Node<Item> next;
}
/**
* Initializes an empty stack.
*/
public Stack() {
first = null;
n = 0;
}
public boolean isEmpty() {
return first == null;
}
public int size() {
return n;
}
public void push(Item item) {
Node<Item> node = new Node<Item>();
node.item = item;
node.next = first;
first = node;
n++;
}
public Item pop() {
if(this.isEmpty())
throw new NoSuchElementException();
Item item = first.item;
first = first.next;
n--;
return item;
}
public Iterator<Item> iterator() {
return new Iterator<Item>() {
private Node<Item> current = first;
public boolean hasNext() {
return current != null;
}
public Item next() {
if(!hasNext())
throw new NoSuchElementException();
Item item = current.item;
current = current.next;
return item;
}
};
}
}
基于数组的实现
import java.util.Iterator;
import java.util.NoSuchElementException;
public class ArrayStack<Item> implements Iterable<Item> {
private static final int DEFAULT_CAPACITY = 10;
private Item[] items;
private int n;
public ArrayStack() {
items = (Item[])new Object[DEFAULT_CAPACITY];
n = 0;
}
public void push(Item item) {
if(n == items.length)
ensureCapacity(2*n + 1);
items[n++] = item;
}
public Item pop () {
if(isEmpty())
throw new NoSuchElementException();
Item item = items[--n];
items[n] = null;
if(n < items.length/4 && items.length/2 > DEFAULT_CAPACITY)
ensureCapacity(items.length/2);
return item;
}
public boolean isEmpty() {
return n == 0;
}
public int size() {
return n;
}
private void ensureCapacity(int nc) {
if(nc < n)
return;
Item[] old = items;
items = (Item[])new Object[nc];
for(int i=0;i<n;i++) {
items[i] = old[i];
}
}
public Iterator<Item> iterator() {
return new Iterator<Item>() {
private int current = n;
public boolean hasNext() {
return n>0;
}
public Item next() {
if(!hasNext())
throw new NoSuchElementException();
return items[--n];
}
};
}
}