Java用队列实现栈(LinkedList中的poll和pop区别)

时间:2025-04-10 14:26:27

LeetCode

使用队列实现栈的下列操作:

push(x) -- 元素 x 入栈
pop() -- 移除栈顶元素
top() -- 获取栈顶元素
empty() -- 返回栈是否为空

解题思路

自己用两个队列实现了栈,是最容易想到的方法,也是数据结构中常规的方法,但是在java中用一个队列也可以容易实现栈。

先给出结论:pop 与 poll 都是取出 LinkedList 的第一个元素,并将该元素删除,等效于:removeFirst

 

不同点:两者的实现所用数据结构不同,

- poll 是基于队列结构实现的方法,当队列中没有元素时,调用该方法返回 null

- pop 是基于栈结构实现的方法,当栈中没有元素时,调用该方法会发生异常

代码实现:

class MyStack {
    Queue<Integer> list;

    /** Initialize your data structure here. */
    public MyStack() {
        list = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        (x);
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        for (int i = 0; i < () - 1; i++) {
            (());
        }
        return ();
    }
    
    /** Get the top element. */
    public int top() {
        for (int i = 0; i < () - 1; i++) {
            (());
        }
        int res = ();
        (res);
        return res;
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return () == null ? true : false;
    }

}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * (x);
 * int param_2 = ();
 * int param_3 = ();
 * boolean param_4 = ();
 */

 

相关文章