首页 > 其他分享 >LeetCode 232. 用栈实现队列

LeetCode 232. 用栈实现队列

时间:2022-08-26 19:11:08浏览次数:58  
标签:int res pop MyQueue 用栈 push LeetCode 232 out

思路:
用两个栈实现队列
pop操作,若out栈为空则先将in中元素push进out,再pop出out中元素
peek操作,直接调用pop,在将pop出元素push进out

class MyQueue {
public:
    stack<int> in;
    stack<int> out;
    MyQueue() {

    }
    
    void push(int x) {
        in.push(x);
    }
    
    int pop() {
        int res;
        if (out.empty()) {
            while (in.size()) {
                out.push(in.top());
                in.pop();
            }
        }

        res = out.top();
        out.pop();

        return res;
    }
    
    int peek() {
        int res = pop();
        out.push(res);

        return res;
    }
    
    bool empty() {
        return in.empty() && out.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();
 * bool param_4 = obj->empty();
 */

标签:int,res,pop,MyQueue,用栈,push,LeetCode,232,out
From: https://www.cnblogs.com/hjy94wo/p/16628894.html

相关文章

  • LeetCode 链表的中间结点算法题解 All In One
    LeetCode链表的中间结点算法题解AllInOnejs/ts实现重排链表链表的中间结点原理图解//快慢指针functionmiddleNode(head:ListNode|null):ListNode|n......
  • LeetCode 每日一题 1302. 层数最深叶子节点的和
    题目链接1302.层数最深叶子节点的和注意事项要用非递归的方式求二叉树深度(即层次遍历BFS)代码classSolution{public:intdeepestLeavesSum(TreeNode*root){......
  • leetcode147:对链表进行插入排序
    packagecom.mxnet;publicclassSolution147{publicstaticvoidmain(String[]args){}/***Q:给定单个链表的头head,使用插入排序对链......
  • leetcode-416-dp
    /**<p>给你一个<strong>只包含正整数</strong>的<strong>非空</strong>数组<code>nums</code>。请你判断是否可以将这个数组分割成两个子集,使得两个子集的元素和相......
  • LeetCode 92. 反转链表 II
    思路将子链表切割下来并记录左节点前一个节点pre和右节点下一个节点sucess反转子链表后,pre指向反转后的子链表,左节点(此时为子链表的尾节点指向sucess)/***Definition......
  • leetcode-数组中两元素的最大乘积
    题目描述给你一个整数数组nums,请你选择数组的两个不同下标i和j,使(nums[i]-1)*(nums[j]-1)取得最大值。请你计算并返回该式的最大值。示例1:输入:nums=[3,4,5,2]......
  • #前端算法救赎系列#LeetCode03.无重复字符的最长子串
    3.无重复字符的最长子串给定一个字符串s,请你找出其中不含有重复字符的最长子串的长度。示例1:输入:s="abcabcbb"输出:3解释:因为无重复字符的最长子串是......
  • [Oracle] LeetCode 415 Add Strings
    Giventwonon-negativeintegers,num1andnum2representedasstring,returnthesumofnum1andnum2asastring.Youmustsolvetheproblemwithoutusingany......
  • leetcode 242. Valid Anagram 有效的字母异位词(简单)
    一、题目大意https://leetcode.cn/problems/valid-anagram给定两个字符串s和t,编写一个函数来判断t是否是s的字母异位词。注意:若s和t中每个字符出现的次数都......
  • leetcode144:二叉树的前序遍历
    packagecom.mxnet;importjava.util.ArrayList;importjava.util.List;publicclassSolution144{publicstaticvoidmain(String[]args){}/**......