剑指offer——面试题9:用两个栈实现队列
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "Queue.h" // ====================测试代码==================== void Test(char actual, char expected) { if(actual == expected) printf("Test passed.\n"); else printf("Test failed.\n"); } 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; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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 }