zoukankan      html  css  js  c++  java
  • 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. }







  • 相关阅读:
    如何将PDF转换成word文档
    pdf转换成word教程
    VMware Net 模式网络配置
    多系统引导-refind
    Linux 磁盘分区调整工具
    Centos 8 安装 docker
    Centos 8 安装 gitlab13
    Centos 8 安装压缩版 mysql-8.0.21-el7-x86_64.tar.gz
    CentOS 添加用户并赋予管理员权限
    Centos 7 防火墙(firewall-cmd)添加端口访问
  • 原文地址:https://www.cnblogs.com/xiejunzhao/p/6493037.html
Copyright © 2011-2022 走看看