码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-03-02 23:32:17      阅读:315      评论:0      收藏:0      [点我收藏+]

标签:href   pad   port   depend   font   note   count   move   oid   

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. }







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

标签:href   pad   port   depend   font   note   count   move   oid   

原文地址:http://www.cnblogs.com/xiejunzhao/p/6493037.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!