main.cpp
/*********************************************** * Problem: 队列中取最大值操作 * 1.EnQueue(V): 将V加入队列中 * 2.DeQueue(): 使队列中首元素删除并返回此元素 * 3.MaxElement(): 返回对列中的最大元素 * * Solution: * 利用两个栈实现队列,在栈中实现取最大元素的操作 *************************************************/ #include <iostream> #include "Stack.h" #include "Queue.h" using namespace std; int main() { Stack<int> s; int a[10]; for(int i=0;i<10;i++) a[i]=rand(); for(int i=0;i<10;i++) { s.Push(a[i]); cout<<a[i]<<" "; } cout<<endl; cout<<s.Max()<<endl; Queue<int> queue; for(int i=0;i<10;i++) queue.EnQueue(a[i]); cout<<"Queue front: "<<queue.DeQueue()<<endl; cout<<"Queue max: "<<queue.Max()<<endl; system("PAUSE"); return 0; }
Stack.h
#ifndef GUARD_stack_h #define GUARD_stack_h #include <iostream> const int MAX_STACK_SIZE=50; template<typename T> class Stack { public: Stack(); void Push(const T& item); T Pop(); T Max() const; bool Empty() const; bool Full() const; private: T stack[MAX_STACK_SIZE]; int top; //最大元素的索引 int maxItemIndex;
//储存着第二大的元素的一组索
int nextMaxItem[MAX_STACK_SIZE]; void Error(char errorMsg[]); }; template<typename T> Stack<T>::Stack() :top(-1),maxItemIndex(-1) { } template<typename T> void Stack<T>::Push(const T& item) { if(top+1==MAX_STACK_SIZE) Error("Stack overflow"); top++; stack[top]=item;
if(item > Max())
{
//储存到栈顶为止,第二大元素的Index
nextMaxItem[top]=maxItemIndex;
maxItemIndex=top;
} else nextMaxItem[top]=-1; } template<typename T> T Stack<T>::Pop() { if(top<0) Error("Stack empty."); T ret=stack[top]; if(top==maxItemIndex) { maxItemIndex=nextMaxItem[top]; } top--; return ret; } template<typename T> T Stack<T>::Max() const { if(maxItemIndex >=0) return stack[maxItemIndex]; else return INT_MIN; } template<typename T> bool Stack<T>::Empty() const { return top==-1; } template<typename T> bool Stack<T>::Full() const { return top+1==MAX_STACK_SIZE; } template<typename T> void Stack<T>::Error(char errorMsg[]) { std::cerr<<errorMsg<<std::endl; exit(1); } #endif
Queue.h
#ifndef GUARD_Queue_h #define GUARD_Queue_h #include "Stack.h" template<typename T> class Queue { public: Queue(); ~Queue(); void EnQueue(const T& item); T DeQueue(); T Max() const; private: Stack<T> *stack1,*stack2; T MaxValue(const T& x,const T& y) const; void Error(char errorMsg[]); }; template<typename T> Queue<T>::Queue() { stack1=new Stack<T>(); stack2=new Stack<T>(); if(stack1==NULL || stack2==NULL) Error("Memory allocation failure."); } template<typename T> Queue<T>::~Queue() { delete stack1; delete stack2; } template<typename T> void Queue<T>::EnQueue(const T &item) { stack2->Push(item); } template<typename T> T Queue<T>::DeQueue() { if(stack1->Empty()) { while(!stack2->Empty()) stack1->Push(stack2->Pop()); } return stack1->Pop(); } template<typename T> T Queue<T>::MaxValue(const T& x,const T& y) const { return x>y ? x:y; } template<typename T> T Queue<T>::Max() const { return MaxValue(stack1->Max(),stack2->Max()); } template<typename T> void Queue<T>::Error(char errorMsg[]) { std::cerr<<errorMsg<<std::endl; exit(1); } #endif