Leetcode之一起攻克栈

之前刷题发现自己对于栈的理解不是很好,所以开一篇文章来写栈。

题目

1.用栈实现队列

题目链接
先来一张队列与栈的图来区分下二者。
在这里插入图片描述
下图为本题的详细题解。
在这里插入图片描述

class MyQueue {
    //存储数据,栈底就是队列的首
    Stack<Integer>stack1;
    //用来中转数据
    Stack<Integer>stack2;
    /** Initialize your data structure here. */
    public MyQueue() {
        stack1 = new Stack<>();
        stack2 = new Stack<>();
    }

    /** Push element x to the back of queue. */
    public void push(int x) {
        //stack1没有的话可以直接插入。
        if(stack1.empty())
            {
                stack1.push(x);
                return ;
            }
        while(!stack1.empty())
            stack2.push(stack1.pop());
        stack2.push(x);
        while(!stack2.empty())
            stack1.push(stack2.pop());
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        return stack1.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        return stack1.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return stack1.empty();
    }
}

/**
 * Your MyQueue object will be instantiated and called as such:
 * MyQueue obj = new MyQueue();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.peek();
 * boolean param_4 = obj.empty();
 */

2.用队列实现栈

题目链接
在这里插入图片描述

class MyStack {
    Queue<Integer>queue1;
    Queue<Integer>queue2;
    /** Initialize your data structure here. */
    public MyStack() {
        queue1 = new LinkedList<>();
        queue2 = new LinkedList<>();
    }
    
    /** Push element x onto stack. */
    public void push(int x) {
        if(queue1.isEmpty())
        {
            queue1.add(x);
            return;
        }
        queue2.add(x);
        while(!queue1.isEmpty())
        {
            queue2.add(queue1.poll());
        }
        Queue<Integer> temp = queue1;
        queue1 = queue2;
        queue2 = temp;
    }
    
    /** Removes the element on top of the stack and returns that element. */
    public int pop() {
        return queue1.poll();
    }
    
    /** Get the top element. */
    public int top() {
        return queue1.peek();
    }
    
    /** Returns whether the stack is empty. */
    public boolean empty() {
        return queue1.isEmpty();
    }
}

/**
 * Your MyStack object will be instantiated and called as such:
 * MyStack obj = new MyStack();
 * obj.push(x);
 * int param_2 = obj.pop();
 * int param_3 = obj.top();
 * boolean param_4 = obj.empty();
 */
发布了55 篇原创文章 · 获赞 28 · 访问量 9254

猜你喜欢

转载自blog.csdn.net/weixin_41796401/article/details/101601988