//============================================================================ // Name : 编程之美队列中取最大值操作问题.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> using namespace std; const int MAXSIZE=10000; class Stack { public: Stack():stackTop(-1),MaxStack(-100){} void push(int date); bool pop(); int Top(); int Max(); void print(); bool empty(); private: int date[MAXSIZE]; int linknextMAX[MAXSIZE]; int stackTop; int MaxStack; }; void Stack::push(int date1) { stackTop++; if(stackTop>=MAXSIZE) return; date[stackTop]=date1; if(date1>MaxStack) { MaxStack=date1; } linknextMAX[stackTop]=MaxStack; } int Stack::Top() { if(stackTop<0) return -100; return date[stackTop]; } int Stack::Max() { if(stackTop<0) return -100; return linknextMAX[stackTop]; } bool Stack::pop() { if(stackTop<0) return false; stackTop--; MaxStack=linknextMAX[stackTop]; return true; } bool Stack::empty() { if(stackTop<0) return true; return false; } void Stack::print() { int number=stackTop; while(number>=0) { cout<<date[number]<<" "; number--; } cout<<endl; number=stackTop; while(number>=0) { cout<<linknextMAX[number]<<" "; number--; } cout<<endl; } class Queue { public: void Enqueue(int date1); int Dequeue(); int MaxElement(); private: Stack s1; Stack s2; }; void Queue::Enqueue(int date1) { s2.push(date1); } int Queue::Dequeue() { if(s1.empty()&&s2.empty()) return -100; int number; if(s1.empty()) { while(!s2.empty()) { number=s2.Top(); s2.pop(); s1.push(number); } } number=s1.Top(); s1.pop(); // cout<<"s1"<<endl; // s1.print(); // cout<<"s2"<<endl; // s2.print(); return number; } int Queue::MaxElement() { int max1=s1.Max(); int max2=s2.Max(); return max1>max2 ? max1 : max2; } int main() { Stack s; s.push(1); s.push(4); s.push(3); s.push(9); s.push(7); s.push(10); s.print(); cout<<"max is "<<s.Max()<<endl; cout<<s.Top()<<endl; s.pop(); s.print(); cout<<"max is "<<s.Max()<<endl; s.pop(); s.pop(); s.print(); cout<<"max is "<<s.Max()<<endl; s.pop(); s.print(); cout<<"max is "<<s.Max()<<endl; s.pop(); s.print(); cout<<"max is "<<s.Max()<<endl; Queue q; q.Enqueue(10); q.Enqueue(4); q.Enqueue(3); q.Enqueue(9); q.Enqueue(7); q.Enqueue(1); cout<<endl<<"max1 is "<<q.MaxElement()<<endl; cout<<"drop "<<q.Dequeue()<<endl;//去掉10 cout<<"max1 is "<<q.MaxElement()<<endl; cout<<"drop "<<q.Dequeue()<<endl; cout<<"drop "<<q.Dequeue()<<endl; //去掉4 3 cout<<"max1 is "<<q.MaxElement()<<endl; cout<<"drop "<<q.Dequeue()<<endl; //去掉9 cout<<"max1 is "<<q.MaxElement()<<endl; q.Enqueue(12); q.Enqueue(2); cout<<"max1 is "<<q.MaxElement()<<endl; return 0; }