zoukankan      html  css  js  c++  java
  • 剑指offer——面试题9:用两个栈实现队列

    #include "Queue.h"
    
    // ====================测试代码====================
    void Test(char actual, char expected)
    {
        if(actual == expected)
            printf("Test passed.
    ");
        else
            printf("Test failed.
    ");
    }
    
    int main(int argc, char* argv[])
    {
        CQueue<char> queue;
    
        queue.appendTail('a');
        queue.appendTail('b');
        queue.appendTail('c');
    
        char head = queue.deleteHead();
        Test(head, 'a');
    
        head = queue.deleteHead();
        Test(head, 'b');
    
        queue.appendTail('d');
        head = queue.deleteHead();
        Test(head, 'c');
    
        queue.appendTail('e');
        head = queue.deleteHead();
        Test(head, 'd');
    
        head = queue.deleteHead();
        Test(head, 'e');
    
        return 0;
    }
    QueueWithTwoStacks.cpp
     1 // 面试题9:用两个栈实现队列
     2 // 题目:用两个栈实现一个队列。队列的声明如下,请实现它的两个函数appendTail
     3 // 和deleteHead,分别完成在队列尾部插入结点和在队列头部删除结点的功能。
     4 
     5 #pragma once
     6 #include <stack>
     7 #include <exception>
     8 #include<stdio.h>
     9 #include<stdexcept>
    10 
    11 using namespace std;
    12 
    13 template <typename T> class CQueue
    14 {
    15 public:
    16     CQueue(void);
    17     ~CQueue(void);
    18 
    19     // 在队列末尾添加一个结点
    20     void appendTail(const T& node);
    21 
    22     // 删除队列的头结点
    23     T deleteHead();
    24 
    25 private:
    26     stack<T> stack1;
    27     stack<T> stack2;
    28 };
    29 
    30 template <typename T> CQueue<T>::CQueue(void)
    31 {
    32 }
    33 
    34 template <typename T> CQueue<T>::~CQueue(void)
    35 {
    36 }
    37 
    38 template<typename T> void CQueue<T>::appendTail(const T& element)
    39 {
    40     stack1.push(element);
    41 }
    42 
    43 template<typename T> T CQueue<T>::deleteHead()
    44 {
    45     if(stack2.size()<= 0)
    46     {
    47         while(stack1.size()>0)
    48         {
    49             T& data = stack1.top();
    50             stack1.pop();
    51             stack2.push(data);
    52         }
    53     }
    54 
    55     if(stack2.size() == 0){
    56         std::logic_error ex("queue is empty");
    57         throw std::exception(ex);
    58     }
    59 
    60     T head = stack2.top();
    61     stack2.pop();
    62 
    63     return head;
    64 }
    Queue.h
  • 相关阅读:
    解析“0”的读法
    CM3 支持 64 位整数, LDRD STRD
    segger usbh struct
    BCM2046 Bluetooth on new 8,3 MacBook Pro USB Interface Descriptor bAlternateSetting
    STM32 USB Host Library 学习笔记 (2) USBH_InterruptSendData() USBH_ClrFeature()
    Double Link List
    汉语拼音方案里的O(哦)和 UO(窝)
    git commit 时,会打开默认的文本编辑器,要求你输入提交信息
    WIN7 常见问题及解决方法
    git 创建 .gitignore 文件 建立项目过滤规则
  • 原文地址:https://www.cnblogs.com/acm-jing/p/10389322.html
Copyright © 2011-2022 走看看