LeetCode-225. 用队列实现栈-Java实现

试题链接

实现效果

数组实现

在这里插入图片描述
代码如下:

class MyStack {
    
        private int[] listOne;
        private int size = 0;
        private int length = 1024;

        /** Initialize your data structure here. */
        public MyStack() {
            listOne = new int[length];
            // listTwo = new ArrayList();
        }

        /** Push element x onto stack. */
        public void push(int x) {
            if(size==length){
                int lastLength = length;
                length = length+lastLength;
                int [] listTemp = new int[length];
                for(int i = 0;i < lastLength;i++){
                    listTemp[i] = listOne[i];
                }
                listOne = listTemp;
            }
            listOne[size++] = x;
        }

        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            return listOne[--size];
        }

        /** Get the top element. */
        public int top() {
            return listOne[size-1];
        }

        /** Returns whether the stack is empty. */
        public boolean empty() {
            if(size==0){
                return true;
            }
            return false;
        }
}

List实现

在这里插入图片描述
代码如下:

import java.util.ArrayList;
import java.util.List;

class MyStack {
    
        private List<Integer> listOne;

        private int size = 0;

        /** Initialize your data structure here. */
        public MyStack() {
            listOne = new ArrayList();
            // listTwo = new ArrayList();
        }

        /** Push element x onto stack. */
        public void push(int x) {
            listOne.add(size,x);
            size++;
        }

        /** Removes the element on top of the stack and returns that element. */
        public int pop() {
            
            return listOne.remove(--size);
        }

        /** Get the top element. */
        public int top() {
            return listOne.get(size-1);
        }

        /** Returns whether the stack is empty. */
        public boolean empty() {
            if(size==0){
                return true;
            }
            return false;
        }
}

过程

这道题没有什么难度,但是使用数组实现(队列毕竟也有数组实现吧,我这样直接用数组不应该算作用队列实现数组)在动态扩容的时候其实不能掌握到正好的大小,并且为了避免扩容1.X倍而带来的浮点型与整型转换的耗时,直接每次添加一个固定值,这样可能会导致数组频繁扩容。
最后要吐槽一下LeetCode的运行信息,完全随机凭心情吧,服务端的环境不能保证一样,这样同样的代码在不同时候产生的结果也不一样,而且测试用例应该也不相同,这样跑出来的时间耗时完全凭运气决定,我放上的两张图片都是效果比较好的。

猜你喜欢

转载自blog.csdn.net/ws948342046/article/details/87800443
今日推荐