首页 > 代码库 > 232. 用栈实现队列 Implement Queue using Stacks

232. 用栈实现队列 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.
Notes:
  • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, 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).
  1. public class MyQueue {
  2. public Stack<int> stack;

  3. public MyQueue() {
  4. stack = new Stack<int>();
  5. }

  6. public void Push(int x) {
  7. stack.Push(x);
  8. }

  9. public int Pop() {
  10. Stack<int> tempStack = new Stack<int>();
  11. int count = stack.Count();
  12. for (int i = 0; i < count; i++) {
  13. tempStack.Push(stack.Pop());
  14. }
  15. int peek = tempStack.Pop();
  16. stack.Clear();
  17. count = tempStack.Count();
  18. for (int i = 0; i < count; i++) {
  19. stack.Push(tempStack.Pop());
  20. }
  21. return peek;
  22. }

  23. public int Peek() {
  24. int[] arr = stack.ToArray();
  25. return arr[stack.Count - 1];
  26. }

  27. public bool Empty() {
  28. return this.stack.Count == 0;
  29. }
  30. }





null


232. 用栈实现队列 Implement Queue using Stacks