算法 1.3节:栈的数组和链表实现

  • 栈的数组实现
import  java.util.Iterator;

public class Stack<T> implements Iterable<T> {
    private T[] stack = (T[])  new Object[1];
    private int N = 0;

    public boolean isEmpty(){
        return N == 0;
    }

    public int size() {
        return N;
    }

    private void resize(int max) {
        T[] temp = (T[]) new Object[max];
        for(int i=0;i<N;i++) {
            temp[i] = stack[i];
        }
        stack = temp;
    }

    public void push(T item) {
        if(N== stack.length)
            resize(2* stack.length);
        stack[N++] = item;
    }

    public T pop () {
        T temp = stack[--N];
        stack[N] = null;
        if(N>0 && N == stack.length/4) resize(stack.length/2);
        return temp;
    }

    public Iterator<T> iterator() {
        return new ReverseIterator();
    }

    private class ReverseIterator implements Iterator<T> {
        private int i =N;

        public boolean hasNext() {
            return i > 0;
        }

        public T next() {
            return stack[--i];
        }

        public void remove() {
        }
    }

}
  • 栈的链表实现
import java.util.Iterator;

public class liststack<T>  implements Iterable<T>{
    private int N;
    private Node first;

    private class Node {
        private T item;
        private Node next;
    }

    public Stack() {
        first = null;
        N = 0;
    }
    boolean isEmpty() {
        return first == null;
    }

    public int size() {
        return N;
    }

    public void push(T item) {
        Node old_first = first;
        first = new Node();
        first.item = item;
        first.next = old_first;
        N++;
    }

    public T pop() {
        T temp = first.item;
        first = first.next;
        N -- ;
        return temp;
    }

    public Iterator<T> iterator() {
        return new ListIterator();
    }

    public class ListIterator implements Iterator<T> {
        private Node current = first;

        public boolean hasNext() {
            return current != null;
        }

        public T next() {
            T item = current.item;
            current = current.next;
            return item;
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值