美文网首页
写一个栈

写一个栈

作者: xin激流勇进 | 来源:发表于2019-04-02 17:41 被阅读0次
    package structures;
    
    public interface Stack<E> {
        int getSize();
        boolean isEmpty();
        E pop();
        E peek();
        void push(E e);
    
    }
    
    package structures;
    
    public class ArrayStack<E> implements Stack<E> {
    
        private Array<E> array;
    
        public ArrayStack(int capacity) {
            array = new Array<>(capacity);
        }
    
        public ArrayStack() {
            array = new Array<>();
        }
    
        public int getCapacity() {
            return array.getCapacity();
        }
    
        @Override
        public int getSize() {
            return array.getSize();
        }
    
        @Override
        public boolean isEmpty() {
            return array.isEmpty();
        }
    
        @Override
        public E pop() {
            return array.removeLast();
        }
    
        @Override
        public E peek() {
            return array.getLast();
        }
    
        @Override
        public void push(E e) {
            array.addLast(e);
        }
    
        @Override
        public String toString() {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("<stack> [");
    
            for (int i = 0; i < array.getSize(); i++) {
                stringBuffer.append(array.get(i));
                if (i != array.getSize() - 1) {
                    stringBuffer.append(",");
                }
            }
    
            stringBuffer.append("] <top>\n");
    
            return stringBuffer.toString();
        }
    }
    
    

    相关文章

      网友评论

          本文标题:写一个栈

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