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

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

2012-12-15 10:39 309 查看
编程之美——队列中取最大值操作问题

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

代码为:
#include<iostream>

#include<vector>

#include<algorithm>

using namespace std;

#define MAXN 100

class stack

{

private:
int stackItem[MAXN];
int stackTop;
int link2NextMaxItem[MAXN];
int maxStackItemIndex;

public:
stack()
{
 stackTop=-1;
 maxStackItemIndex=-1;
}
void push(int x)
{
 stackTop++;
 if(stackTop>=MAXN)
 return;
 stackItem[stackTop]=x;
 if(x>max())
 {
   link2NextMaxItem[stackTop]=maxStackItemIndex;
maxStackItemIndex=stackTop;
 }
 else
 link2NextMaxItem[stackTop]=-1;
}
int pop()
{
 if(stackTop>=0)
 {
  int ret=stackItem[stackTop];
  if(stackTop==maxStackItemIndex)
  {
    maxStackItemIndex=link2NextMaxItem[stackTop];
  }
  stackTop--;
  return ret;
 }
}
int max()
{
 if(maxStackItemIndex>=0)
 return stackItem[maxStackItemIndex];
 else return -10000;
}
bool empty()
{
 return stackTop==-1;
}

};

class Queue

{

public:
stack s1;
stack 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()

{

  stack stk;

  stk.push(1);

  stk.push(4);

  stk.push(2);

  stk.push(8);

  for(int i=0;i<4;i++)

  {

    cout<<stk.pop()<<" ";
cout<<"max value:"<<stk.max()<<endl;

  }

  Queue queue;

  queue.enque(8);

  queue.enque(4);

  queue.enque(2);

  queue.enque(1);

  for(int j=0;j<4;j++)

  {

    cout<<queue.deque()<<" ";
cout<<"max value:"<<queue.max()<<endl;

  }

  system("pause");

  return 0;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: