• 【面试题7】用两个栈实现队列


    【题目描述】

    用两个栈实现一个队列。队列的声明如下,请实现他的两个函数AppendTail和DeleteHead,分别完成在队尾部插入结点和在队头删除结点的功能。

    【解决方案】

    stackAppend栈用来添加,stackDelete栈用于删除,当stackDelete栈没有元素时,则从stackAppend栈往stackDelete栈压入元素,再进行删除。看代码和图例你就懂了。

    我的实现代码,仅供参考:

     1     class MyQueue<T>
     2     {
     3         Stack<T> stackAppend = new Stack<T>();
     4         Stack<T> stackDelete = new Stack<T>();
     5 
     6         public void AppendTail(T value)
     7         {
     8             stackAppend.Push(value);
     9         }
    10 
    11         public T DeleteHead()
    12         {
    13             if (stackDelete.Count <= 0)
    14             {
    15                 while (stackAppend.Count > 0)
    16                 {
    17                     stackDelete.Push(stackAppend.Pop());
    18                 }
    19             }
    20             if (stackDelete.Count <= 0)
    21                 throw new Exception("Queue is empty.");
    22             return stackDelete.Pop();
    23         }
    24     }

    【本题扩展】

    用两个队列实现一个栈。

    我的实现代码,仅供参考:

     1     class MyStack<T>
     2     {
     3         Queue<T> queueA = new Queue<T>();
     4         Queue<T> queueB = new Queue<T>();
     5 
     6         public void Push(T value)
     7         {
     8             if (queueA.Count > 0)
     9             {
    10                 queueA.Enqueue(value);
    11             }
    12             else
    13             {
    14                 queueB.Enqueue(value);
    15             }
    16         }
    17 
    18         public T Pop()
    19         {
    20             if (queueA.Count > 0)
    21             {
    22                 while (queueA.Count > 1)
    23                 {
    24                     queueB.Enqueue(queueA.Dequeue());
    25                 }
    26                 return queueA.Dequeue();
    27             }
    28             else if (queueB.Count > 0)
    29             {
    30                 while (queueB.Count > 1)
    31                 {
    32                     queueA.Enqueue(queueB.Dequeue());
    33                 }
    34                 return queueB.Dequeue();
    35             }
    36             else
    37             {
    38                 throw new Exception("Stack is empty.");
    39             }
    40         }
    41     }

     

  • 相关阅读:
    生成word附件和word域动态赋值
    查询结果用Object类或其数组的List接收
    mustache多次渲染和多个赋值
    规范必备:枚举类型
    使用HttpClient发送请求、接收响应
    java接口对接——别人调用我们接口获取数据
    java接口对接——调用别人接口推送数据
    mustache语法
    Confluence 6 空间标识
    Confluence 6 从一个模板中创建一个空间
  • 原文地址:https://www.cnblogs.com/HuoAA/p/4798493.html
Copyright © 2020-2023  润新知