本文主要是介绍面试题7:用两个栈实现队列,队列的声明如下,请实现它的两个函数appendTail和deleteHead, 分别完成在队列尾部插入结点和在队列头部删除节点的功能。,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
/*面试题7:用两个栈实现队列,队列的声明如下,请实现它的两个函数appendTail和deleteHead,分别完成在队列尾部插入结点和在队列头部删除节点的功能。template<typename T> class CQueue{public:CQueue(void);~CQueue(void);void appendTail(const T& node);T deleteHead();private:stack<T> stack1;stack<T> stack2;}
*/#include "stadfx.h"
//
#include "iostream"
#include "Queue.h"void Test(char actual, char excepted)
{if(actual== excepted)printf("Test passed.\n");elseprintf("Test failed.\n");
}int _tmain(int argc, _TCHAR *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');//system("pause");return 0;}
#pragma once#include <stack>#include <exception>
using namespace std;template <typename T>class CQueue
{
public:CQueue(void);~CQueue(void);// 在队列末尾添加一个结点void appendTail(const T& node);// 删除队列的头结点T deleteHead();private:stack<T> stack1;stack<T> stack2;
};template<typename T>CQueue<T>::CQueue(void)
{
}template<typename T>CQueue<T>::~CQueue(void)
{
}template<typename T>void CQueue<T>::appendTail(const T& element)
{stack1.push(element);
}template<typename T>T CQueue<T>::deleteHead()
{if(stack2.size() <= 0){while(stack1.size() > 0){T& data = stack1.top();stack1.pop();stack2.push(data);}}if(stack2.size() == 0)throw new exception("queue is empty");T head = stack2.top();stack2.pop();return head;
}
#include "Queue.h"
//
#include "stadfx.h"
#include <queue>
#pragma once#include "targetver.h"#include "stdio.h"
#include "tchar.h"
#include "stadfx.h"
#pragma once#ifndef _WIN32_WINNT // Specifies that the minimum required platform is Windows Vista.
#define _WIN32_WINNT 0x0600 // Change this to the appropriate value to target other versions of Windows.#endif
这篇关于面试题7:用两个栈实现队列,队列的声明如下,请实现它的两个函数appendTail和deleteHead, 分别完成在队列尾部插入结点和在队列头部删除节点的功能。的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!