Author Avatar
Brian Lee 7月 25, 2018
  • 在其它设备中阅读本文章

《Algorithm》(Sedgewick)笔记:栈


特点

  • 基于后进先出(LIFO)策略

API

public class Stack<Item> implements Iterable<Item>

Stack() 创建一个空栈
void push(Item item) 添加一个元素
Item pop() 删除最近添加的元素
boolean isEmpty() 栈是否为空
int size() 栈中的元素数量

实现

数组实现

  • 能够动态调整数组大小
public class ResizingArrayStack<Item> implements Iterable<Item> {
    private Item[] a = (Item[]) new Object[1];
    private int N = 0;
    public boolean isEmpty() { return N == 0; }
    public int size() { return N; }
    private void resize(int max) {
        Item[] temp = (Item[]) new Object[max];
        for (int i = 0; i < N; i++)
            temp[i] = a [i];
        a = temp;
    }
    public void push(Item item) {
        if (N == a.length)
            resize(2 * a.length);
        a[N++] = item;
    }
    public Item pop() {
        Item item = a[--N];
        a[N] = null;
        if (N > 0 && N == a.length / 4)
            resize(a.length / 2);
        return item;
    }
    public Iterator<Item> iterator() {
        return new ReverseArrayIterator();
    }
    private class ReverseArrayIterator implements Iterator<Item> {
        private int i = N;
        public boolean hasNext() { return i > 0; }
        public Item next() { return a[--i]; }
        public void remove(){ }
    }
}

链表实现

public class Stack<Item> implements Iterable<Item> {
    private class Node {
        Item item;
        Node next;
    }
    private Node first;     //栈顶
    private int N;          //元素数量
    public boolean isEmpty() { return N == 0; }
    public int size() { return N; }
    public void push(Item item) {
        Node oldFirst = first;
        first = new Node();
        first.item = item;
        first.next = oldFirst;
        N ++;
    }
    public Item pop() {
        Item item = first.item;
        first = first.next;
        N --;
        return item;
    }
    //支持迭代,可以没有
    public Iterator<Item> iterator() {
        return new ListIterator();
    }
    private class ListIterator implements Iterator<Item> {
        private Node current = first;
        public boolean hasNext() { return current != null; }
        public void remove() { }
        public Item next() {
            Item item = current.item;
            current = current.next;
            return item;
        }
    }
}

源码地址

https://github.com/XutongLi/Algorithm-Learn/tree/master/src/S1_foundation/S1_3_BagQueueStack/S1_3_2_5_ResizingArrayStack

https://github.com/XutongLi/Algorithm-Learn/tree/master/src/S1_foundation/S1_3_BagQueueStack/S1_3_3_8_Stack

本博客采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
本文链接:http://brianleelxt.top/2018/07/25/Stack/