泛型

泛型接口

public interface MinStackContract {
    public boolean isEmpty();
    public int size();
    public Item pop();
    public Item min();
    public void push(Item item);
}

实现栈需要能够返回最小值,且为O(1),也就意味着,栈中存储的元素必须是可以比较的,因此设计了这个接口,约束其中的类型。替代Comparable的可以是一个接口或者是一个类,这里不能使用implements关键字。

泛型接口实现

public class MinStack implements MinStackContract {
    private class Node {
        Item item;
        Item min;
        Node next;
    }
    private Node top;
    private int size = 0;
    public boolean isEmpty() {
        return top == null;
    }

    public int size(){
        return size;
    }

    public void push(Item item) {
        Node node = new Node();
        node.item = item;
        node.next = top;
        size++;
        top = node;
        if (size() == 1)
        {
            top.min = item;
        }else {
            //如果没有对泛型使用Comparable约束,这里直接使用>比较会报错。
            if (top.next.min.compareTo(item) == 1){
                top.min = item;
            }else {
                top.min = top.next.min;
            }
        }
    }
    public Item pop() {
        if (isEmpty()){
            throw new NullPointerException("stack is empty");
        }
        Item item = top.item;
        //删除栈顶元素
        top = top.next;
        size--;

        return item;
    }

    public Item min() {
        if (isEmpty()){
            throw new NullPointerException("stack is empty");
        }
        return top.min;
    }
}

你可能感兴趣的:(泛型)