LeetCode--Implement Queue using Stacks

喜欢ヅ旅行 2022-08-17 16:07 111阅读 0赞

Problem:

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.
Notes:
- You must use onlystandard operations of a stack – which means only push to top,peek/pop from top, size, and is 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).

Analysis:
题意:用栈实现队列
用两个堆栈实现,一个放push的数据,另一个放pop的数据,但是在pop在前需要将push栈中的数据push到pop栈中,这样就可以使pop先进先出了。
注意:

  • 堆栈的输入元素是对象,所以需要定义Integer类型
  • pop时应该先pop堆栈(pop的),如果为空就要将push堆栈的数据push到pop堆栈中,然后再pop出去。
  • peek需要返回int类型,所以注意输出时return,不要忘了。
  • 判断是否为空主要是判断两个栈是否同时为空。

Anwser:

  1. class MyQueue {
  2. // Push element x to the back of queue.
  3. Stack<Integer> in = new Stack<>();
  4. Stack<Integer> out = new Stack<>();
  5. public void push(int x) {
  6. in.push(x);
  7. }
  8. // Removes the element from in front of queue.
  9. public void pop() {
  10. if (!out.empty()) out.pop();
  11. else {
  12. while(!in.empty()) out.push(in.pop());
  13. out.pop();
  14. }
  15. }
  16. // Get the front element.
  17. public int peek() {
  18. if (!out.empty()) return out.peek();
  19. else {
  20. while(!in.empty()) out.push(in.pop());
  21. return out.peek();
  22. }
  23. }
  24. // Return whether the queue is empty.
  25. public boolean empty() {
  26. if(in.empty()&& out.empty()) return true;
  27. else return false;
  28. }
  29. }

发表评论

表情:
评论列表 (有 0 条评论,111人围观)

还没有评论,来说两句吧...

相关阅读