C++编程之美-结构之法(代码清单3-9)

代码清单3-9

class stack
{
public:

     stack()
     {
          stackTop = -1;
          maxStackItemIndex = -1;
     }
     void Push(Type x)
     {
          stackTop++;
          if(stackTop >= MAXN)
               ;        //超出栈的最大存储量
          else
          {
               stackItem[stackTop] = x;
               if(x > Max())
               {
                    link2NextMaxItem[stackTop] = maxStackItemIndex;
                    maxStackItemIndex = stackTop;
               }
               else
                    link2NextMaxItem[stackTop] = -1;
          }
     }

     Type Pop()
     {
          Type ret;
          if(stackTop < 0)
               ThrowException();    //已经没有元素了,所以不能pop
          else
          {
               ret = stackItem[stackTop];
               if(stackTop == maxStackItemIndex)
               {
                    maxStackItemIndex = link2NextMaxItem[stackTop];
               }
               stackTop--;
          }
          return ret;
     }

     Type Max()
     {
          if(maxStackItemIndex >= 0)
               return stackItem[maxStackItemIndex];
          else
               return –INF;
     }

private:

     Type stackItem[MAXN];
     int stackTop;
     int link2NextMaxItem[MAXN];
     int maxStackItemIndex; 
}
发布了1242 篇原创文章 · 获赞 951 · 访问量 7万+

猜你喜欢

转载自blog.csdn.net/weixin_42528266/article/details/104028049