您的位置:首页 > 编程语言

编程之美3.7队列中取最大值操作

2014-08-31 22:30 218 查看
/*
编程之美3.7队列中取最大值操作
采用STL中的已有stack
方法:用的文中的方法3:保存栈中最大值可以简单实现
*/
#include<stack>
#include<iostream>
using namespace std;
template<typename T>
class Queue
{
public:
void push(T data)
{
stackIn.push(data);
if(stackInCopy.empty())
stackInCopy.push(data);
else if(stackInCopy.top()<data)
{
stackInCopy.push(data);
}
else
{
stackInCopy.push(stackInCopy.top());
}
}
T pop()
{
if(stackOut.empty())
{
while(!stackIn.empty())
{
T temp=stackIn.top();
stackIn.pop();
stackOut.push(temp);
stackInCopy.pop();
if(stackOutCopy.empty())
{
stackOutCopy.push(temp);
}
else if(stackOutCopy.top()<temp)
{
stackOutCopy.push(temp);
}
else
{
stackOutCopy.push(stackOutCopy.top());
}
}
}

T result=stackOut.top();
stackOut.pop();
stackOutCopy.pop();

return result;

}
T maxElement()
{
if(stackOutCopy.empty()&&stackInCopy.empty())
{
return INT_MIN;
}
else if(stackOutCopy.empty())
{
return stackInCopy.top();
}
else if(stackInCopy.empty())
{
return stackOutCopy.top();
}
else
{
return MAX(stackOutCopy.top(),stackInCopy.top());
}
}

private:
T MAX(T x,T y)
{
if(x>y)
return x;
else
return y;
}
stack<T> stackIn;
stack<T> stackInCopy;
stack<T> stackOut;
stack<T> stackOutCopy;
};
void main()
{
Queue<int> q;
q.push(1);
cout<<q.maxElement()<<endl;
q.push(2);
cout<<q.maxElement()<<endl;
q.push(3);
cout<<q.maxElement()<<endl;
q.push(4);
cout<<q.maxElement()<<endl;
cout<<q.pop()<<endl;
cout<<q.maxElement()<<endl;
cout<<q.pop()<<endl;
cout<<q.maxElement()<<endl;
cout<<q.pop()<<endl;
cout<<q.maxElement()<<endl;
cout<<q.pop()<<endl;
cout<<q.maxElement()<<endl;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: