栈
API
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import java.util.Iterator;
public class Stack<E> implements Iterable<E> {
void push(E element);
public E pop();
public int size();
public boolean isEmpty();
@Override public Iterator<E> iterator(); }
|
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| public class Stack<E> implements Iterable<E> {
private static class Node<T> { Node<T> next; T item;
Node(Node<T> next, T item) { this.next = next; this.item = item; } }
private Node<E> top;
private int size;
void push(E element) { top = new Node<>(top, element); size++; }
public E pop() { if (isEmpty()) { throw new IllegalArgumentException("empty stack"); } Node<E> temp = top; top = top.next; temp.next = null; size--; return temp.item; }
public int size() { return size; }
public boolean isEmpty() { return top == null; }
@Override public Iterator<E> iterator() { return new StackIterator(); }
private class StackIterator implements Iterator<E> { Node<E> current = top;
@Override public boolean hasNext() { return current != null; }
@Override public E next() { Node<E> oldCurrent = current; current = current.next; return oldCurrent.item; } } }
|
测试
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| public static void main(String[] args) { Stack<Integer> stack = new Stack<>(); for (int i = 0; i < 5; i++) { stack.push(i); } System.out.println("stack size is : " + stack.size());
for (int i : stack) { System.out.print(i); } System.out.println(); for (int i = 0; i < 5; i++) { stack.pop(); } System.out.println("stack size is : " + stack.size()); System.out.println("stack is empty : " + stack.isEmpty()); }
|