java 栈的实现


接口定义
interface Stack<T> {
    public T pop();
    public void push(T element);
    public boolean isEmpty();
    public T peek();
}

接口实现:链表方式
class LinkedStack<T> implements Stack<T>{
    //不用容器或者数组等数据结构存储节点
    //Node定义一个节点类
    private class Node<U>{
        private U item; //存储的data
        private Node<U> next; //类似指针
        Node(){
            this.item = null;
            this.next = null;
        }
        Node(U item, Node<U> next){
            this.item = item;
            this.next = next;
        }
        boolean end(){
            return item == null && next == null;
        }
    } 


    private Node<T> top ; //栈顶指针
    LinkedStack(){
        top = new Node<T>();
    }




    //弹栈
    public T pop(){
        if(this.isEmpty() == true){
            throw new EmptyStackException();
        }
        T result = top.item;
        if(!top.end())
        {
            top = top.next;
        }
        return result;
    }
    //压栈
    public void push(T element){
        top = new Node<T>(element, top);
    }
    //判断是否为空
    public boolean isEmpty(){
        return  top.end();
    }
    //返回栈顶元素
    public T peek(){
        if(this.isEmpty() == true){
            throw new EmptyStackException();
        }
        T result = top.item;
        return result;
    }   
}
接口实现:容器方式 
class StackList<T> implements Stack<T> {
    private List<T> list ; //用容器实现
    StackList(){
        list = new ArrayList<T>();
    }
    //弹栈
    public T pop(){
        if(this.isEmpty() == true){
            throw new EmptyStackException();
        }


        return list.remove(list.size()-1);
    }
    //压栈
    public void push(T element){
        list.add(element);
    }
    //判断是否为空
    public boolean isEmpty(){
        return list.size() == 0;
    }
    //返回栈顶元素
    public T peek(){
        if(this.isEmpty() == true){
            throw new EmptyStackException();
        }
        return list.get(list.size()-1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值