LeetCode 之 Implement Queue using Stacks — C++ 实现
来源:互联网 发布:evc手绘视频软件 编辑:程序博客网 时间:2024/05/06 06:16
Implement Queue using Stacks
Implement the following operations of a queue using stacks.
- push(x) -- Push element x to the back of queue.
- pop() -- Removes the element from in front of queue.
- peek() -- Get the front element.
- empty() -- Return whether the queue is empty.
- You must use only standard operations of a stack -- which means only
push to top
,peek/pop from top
,size
, andis empty
operations are valid. - Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
- You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).
- push(x) -- 将元素放入队尾。
- pop() -- 移除队列头的元素。
- peek() -- 返回队列头元素。
- empty() -- 返回队列是否为空。
- 只能使用栈的标准操作--即
push to top
,peek/pop from top
,size
,和 is empty 合法。 - 使用的语言不一定有栈结构,但可以使用链表或队列模拟栈,只要使用栈的标准操作就可以。
- 假设所有操作都合法(例如,当队列空时不会执行 pop 和 peek 操作)。
因为栈是 FILO 结构,队列是 LIFO 结构,入队操作和压栈操作一样,但是出栈操作和出队操作相反,可以使用辅助栈,出队时将数据压入辅助栈,返回栈底(队头)元素后再将元素存回原来的栈。
class Queue {public: // Push element x to the back of queue. void push(int x) { squeue.push(x); } // Removes the element from in front of queue. void pop(void) { stack<int> temp; stackSwap(squeue, temp); temp.pop(); stackSwap(temp, squeue); return; } // Get the front element. int peek(void) { int ret = 0; stack<int> temp; stackSwap(squeue, temp); ret = temp.top(); stackSwap(temp, squeue); return ret; } // Return whether the queue is empty. bool empty(void) { return squeue.empty(); } void stackSwap(stack<int> &src, stack<int> &dst) { int srcSize = src.size(); for(int i = 0; i < srcSize; ++i) { dst.push(src.top()); src.pop(); } return; } private: stack<int> squeue;};
0 0
- LeetCode 之 Implement Queue using Stacks — C++ 实现
- Leetcode-Implement Queue using Stacks(C++)
- 【LeetCode-232】 Implement Queue using Stacks(C++)
- leetcode之Implement Queue using Stacks
- leetcode之 Implement Queue using Stacks
- leetcode之Implement Queue using Stacks
- leetcode :Implement Queue using Stacks
- [LeetCode] Implement Queue using Stacks
- LeetCode Implement Queue using Stacks
- LeetCode || Implement Queue using Stacks
- leetcode Implement Queue using Stacks
- Leetcode Implement Queue using Stacks
- [LeetCode]Implement Queue using Stacks
- 【Leetcode】Implement Queue using Stacks
- LeetCode Implement Queue using Stacks
- Leetcode: Implement Queue using Stacks
- [leetcode] Implement Queue using Stacks
- 【leetcode】Implement Queue using Stacks
- mysql的使用
- HDU 2041 超级楼梯
- JS高级程序设计3-基本概念
- chapter17test5
- 在头文件中添加文件注释
- LeetCode 之 Implement Queue using Stacks — C++ 实现
- java学习之旅56--数组_StringBuilder和StringBuffer的使用_常用方法_方法链的实现_JDK源码分析
- POJ 2886 Who Gets the Most Candies?(线段树)
- springmvc+mybatis登录功能
- kaggle-电影评分预测从零开始
- 1.写一个Mvc框架_超轻量级MVC框架的设计和实现
- android中线程的同步
- ORACLE ADF Summit示例程序的一些问题
- C++笔记(5):指针