程序员面试100题之十八 十四 两个栈实现队列

来源:互联网 发布:sql增删改查语句 编辑:程序博客网 时间:2024/06/09 18:54
// 程序员面试100题之十八 两个栈实现队列.cpp : 定义控制台应用程序的入口点。//#include "stdafx.h"#include <stack>#include <queue>#include <iostream>using namespace std;template<typename T> class CQueue{public:CQueue() {}~CQueue() {}//void appendTail(const T& node);  // append a element to tail//void deleteHead();               // remove a element from head //T getFront();//bool isEmpty();void CQueue<T>::appendTail(const  T& node);void CQueue::deleteHead(){if (m_stack2.empty()==0)// is not empty{m_stack2.pop();}else{while(m_stack1.empty()==0){T temp;temp = m_stack1.top();m_stack2.push(temp);m_stack1.pop();}if (m_stack2.empty()==0){m_stack2.pop();}}}T CQueue::getFront(){if (m_stack2.empty()==0){return m_stack2.top();}}bool CQueue::isEmpty(){if (m_stack2.empty()==0)// is not empty{return false;}else{while(m_stack1.empty()==0){T temp;temp = m_stack1.top();m_stack2.push(temp);m_stack1.pop();}if (m_stack2.empty()==0){return false;}else{return true;}}}private:stack<T> m_stack1;//serve as the input stackstack<T> m_stack2;//serve as the output stack};template<typename T> void CQueue<T>::appendTail(const  T& node)// defination outside the class, <T> must be followed after CQueue{m_stack1.push(node);}template<typename T> class CStack{public:CStack(){};~CStack(){};void Push(const T& node){que1.push(node);}T Top(){if (que1.empty()==0){while(que1.size()>1){T temp;temp = que1.back();que1.pop();que2.push(temp);}T ret = que1.back();while (que2.empty()==0){T temp;temp = que2.back();que2.pop();//back que1.push(temp);//}return ret;}}void Pop(){if (que1.empty()==0){while(que1.size()>1){T temp;temp = que1.front();//front outque1.pop();que2.push(temp);}que1.pop();//deletewhile (que2.empty()==0){T temp;temp = que2.front();que2.pop();//back inque1.push(temp);//}}}private:queue<T> que1,que2;//};
bool isPushPop( string str1,string str2)// 100题24,判断是否为Push,Pop序列{//没有判断输入是否合法,不健壮stack<char> stk;int i=0,j=0;while(i<=str1.length()&&j<=str2.length()){char ch1;ch1=str2[j];if (stk.empty()==0){if(stk.top()==ch1){stk.pop();j++;}elsereturn false;}else{for(int k=i;str1[k]!=ch1;k++){stk.push(str1[k]);i++;}stk.push(ch1);i++;}if(i==str1.length()&&j==str2.length())return true;}}
int _tmain(int argc, _TCHAR* argv[]){CQueue<int> cque1;//cstk1 = new CQueue<int>(),cstk2 = new CQueue<int>();for (int i=0;i<10;i++){cque1.appendTail(i*2);}for (int i=0;i<5;i++){cque1.deleteHead();}for (int i=10;i<15;i++){cque1.appendTail(i*2);}CStack<int> cstk1;//cstk1 = new CQueue<int>(),cstk2 = new CQueue<int>();for (int i=0;i<10;i++){cstk1.Push(i*2);}for (int i=0;i<5;i++){cstk1.Pop();}for (int i=10;i<15;i++){cstk1.Push(i*2);}string str1="ABCDE",str2="BAEDC";cout<<" is "<<isPushPop(str1,str2);system("pause");return 0;}