A Za, A Za, Fighting...

坚信:勤能补拙

设计包含min函数的栈

题目出处: http://zhedahht.blog.163.com/blog/static/25411174200712895228171/

题目:定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数minpush以及pop的时间复杂度都是O(1)
#include "StackWithMin.h"
#include
<cstdio>
#include
<cstdlib>
#include
<cstring>

const int StackWithMin::MAX_SIZE ;

StackWithMin::StackWithMin() :
    top_index(
-1), min_index(-1)
{
    printf(
"StackWithMin Constructor\n");
}

StackWithMin::
~StackWithMin()
{
    printf(
"StackWithMin Destructor\n");
}

int
StackWithMin::top() 
const
{
    
if(top_index == -1) {
        printf(
"top() failed: Stack Empty\n");
        
return -1;
    }

    
return stack[top_index]; 
}

int
StackWithMin::get_min() 
const
{
    
if(min_index == -1) {
        printf(
"get_min() failed: Stack Empty\n");
        
return -1;
    }

    
return stack[min_index];
}

void
StackWithMin::push(
int value)
{
    
if(top_index == -1) { /* stack empty */
        stack[
++top_index] = value;
        min_index 
= top_index;
        
return;
    }
    stack[
++top_index] = value;
    
if(value < stack[min_index]) {
        index[top_index] 
= min_index;
        min_index 
= top_index;
    }
}

int
StackWithMin::pop()
{
    
if(top_index == -1) {
        printf(
"pop() failed: Stack Empty\n");
        
return -1;
    }
    
int ret = stack[top_index];
    
if(min_index == top_index)
        min_index 
= index[top_index];
    
--top_index;
    
return ret;
}



class StackWithMin
{
    public:
        StackWithMin();
        ~StackWithMin();
        int get_min() const;
        int top() const;
        void push(int value);
        int pop();      
    private:
        static const int MAX_SIZE = 101;
        int top_index, min_index;
        int stack[MAX_SIZE];
        int index[MAX_SIZE];
};









posted on 2011-05-25 15:49 simplyzhao 阅读(236) 评论(0)  编辑 收藏 引用 所属分类: M_面试题集锦


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


导航

<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678

统计

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

最新评论

阅读排行榜

评论排行榜