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

编程之美-队列中取最大值操作问题

2011-04-17 10:17 274 查看
这是一个要在队列中记录最大值的问题,但每次进队或出队又不能通过遍历去检测最大值的变化。用两个堆栈去实现一个队列是比较常见的方法,书中巧妙的用到了此方法,这样问题就转化为堆栈中取最大值操作问题。由于堆栈的变化只在栈顶,借助反向推导的思想:

由于在PUSH的过程中,最大值只与某一些值有关,这些值会在PUSH的过程中形成一个有序的链式结构。如PUSH(1,4,2,8)那么这个有序序列为(1,4,8) 所以当8被POP时,最大值会回到4,4被POP时,最大值会回到1,整个过程与2无关。所以可以用一个数组记录下当堆栈中某一个数被POP后,下一个最大值在堆栈中的位置。

#include<iostream>
using namespace std;
#include<vector>
#include<algorithm>
class maxstack
{
private:
int mystack[1000];
int top;
int link2nextMax[1000];
int curmaxindex;
public:
maxstack()
{
top=-1;
curmaxindex=-1;
}
void push(int x)
{
top++;
mystack[top]=x;
if(x>max())
{
link2nextMax[top]=curmaxindex;
curmaxindex=top;
}
else
link2nextMax[top]=-1;
}
int pop()
{
if(top>=0)
{
int popout=mystack[top];
if(popout==mystack[curmaxindex])
{
curmaxindex=link2nextMax[top];
}
top--;
return popout;
}
}
int max()
{
if(curmaxindex>=0) return  mystack[curmaxindex];
else return -5622;
}
bool empty()
{
return top==-1;
}
};
class maxque
{
private:
maxstack s1;
maxstack s2;
public:
void enque(int x)
{
s1.push(x);
}
int deque()
{
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.pop());
}
}
return s2.pop();
}
int max()
{
return maxvalue(s1.max(),s2.max());
}
int maxvalue(int x,int y)
{
return x>y?x:y;
}
};
int main()
{
maxstack mxt;
mxt.push(1);
mxt.push(4);
mxt.push(2);
mxt.push(8);
for(int i=0;i<4;i++)
{
cout<<mxt.pop();
cout<<"max:"<<mxt.max();
cout<<endl;
}
maxque mxq;
mxq.enque(8);
mxq.enque(4);
mxq.enque(2);
mxq.enque(1);
for(int i=0;i<4;i++)
{
cout<<mxq.deque();
cout<<"max:"<<mxq.max();
cout<<endl;
}
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: