美文网首页数据结构
栈的实现(基于动态数组)

栈的实现(基于动态数组)

作者: 小小飞的救赎 | 来源:发表于2018-09-13 11:47 被阅读0次

    先定义一个接口

    public interface Stack<E> {
        int getSize();
        boolean isEmpty();
        boolean contains(E e);
        //入栈
        void push(E e);
        //查看栈顶的数据
        E peek();
        //出栈
        E pop();
    }
    

    再定义一个栈的实现类,实现上述接口

    /**
     * 基于数组实现栈
     * @author hcc
     *
     */
    public class HArrayStack<E> implements Stack<E> {
        private HGenericityArrayList<E> data;
        public HArrayStack() {
            data = new HGenericityArrayList<E>();
        }
        public HArrayStack(int capacity) {
            data = new HGenericityArrayList<E>(capacity);
        }
        public int getCapacity() {
            return data.getCapacity();
        }
        @Override
        public int getSize() {
            // TODO Auto-generated method stub
            return data.getSize();
        }
    
        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return data.isEmpty();
        }
    
        @Override
        public boolean contains(E e) {
            // TODO Auto-generated method stub
            return data.contains(e);
        }
    
        @Override
        public void push(E e) {
            // TODO Auto-generated method stub
            data.add(e);
        }
    
        @Override
        public E peek() {
            // TODO Auto-generated method stub
            return data.get(data.getSize()-1);
        }
    
        @Override
        public E pop() {
            // TODO Auto-generated method stub
            return data.remove(data.getSize()-1);
        }
        @Override
        public String toString() {
            StringBuilder str = new StringBuilder();
            str.append("HArrayStack:");
            str.append(data);
            return str.toString();
        }
        
    }

    相关文章

      网友评论

        本文标题:栈的实现(基于动态数组)

        本文链接:https://www.haomeiwen.com/subject/oklwgftx.html