• 用栈实现队列


    此博客链接:https://www.cnblogs.com/ping2yingshi/p/13377164.html

    题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/

    用栈实现队列

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

    push(x) -- 将一个元素放入队列的尾部。
    pop() -- 从队列首部移除元素。
    peek() -- 返回队列首部的元素。
    empty() -- 返回队列是否为空。
     

    示例:

    MyQueue queue = new MyQueue();

    queue.push(1);
    queue.push(2);
    queue.peek(); // 返回 1
    queue.pop(); // 返回 1
    queue.empty(); // 返回 false
     

    说明:

    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。

    题解:

            思路:栈是先进后出,而队列是先进先出,在栈中只能在一端插入删除,而在队列中是在一端插入,另外一端删除,当使用栈实现队列时,队列的删除,取队顶元素,判断队列是否为空,都和栈的操作时一致的,在栈的一端操作即可达到效果,但是队列的插入操作是在另外一端实现的,这里使用栈的实现队列的话,即在栈底插入,但是对于栈只能在栈定进行操作,所以要想把插入的元素放到栈底,需要借助另外一个栈,先把当前栈中的元素都放到新的栈中,最后把插入的元素插入到栈顶,再把新栈中的元素全部重新进入到栈中,此时,插入的元素就在栈底了。             

    代码:

    class MyQueue {
        Stack <Integer> stack=new Stack<>();
    
        /** Initialize your data structure here. */
        public MyQueue() {
    
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            if(!stack.empty())
            {
            Stack <Integer> stack1=new Stack<>(); 
            while(!stack.empty())
            {
                stack1.push(stack.pop());
            }
            stack1.push(x);
            while(!stack1.empty())
            {
               stack.push(stack1.pop());
            }
            }
            else 
            stack.push(x);
    
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
          return stack.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            return stack.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
      
                return stack.empty();
          
        }
    }
  • 相关阅读:
    [LintCode] 最长上升子序列
    [LintCode] 最长公共前缀
    [LintCode] A + B 问题
    [hihoCoder] 拓扑排序·一
    [LintCode] 拓扑排序
    [LintCode] 第k大元素
    [LintCode] 最小路径和
    [LeetCode] Factorial Trailing Zeros
    [LintCode] 尾部的零
    [LeetCode] Length of Last Word
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/13377164.html
Copyright © 2020-2023  润新知