100题_02 设计包含min函数的栈

题目:定义栈的数据结构,要求添加一个min函数,能够得到栈的最小元素。要求函数min、push以及pop的时间复杂度都是O(1)。

 

分析:这题的主要限制在时间复杂度为O(1),首先想到的肯定是以空间换时间。这里我们给栈里面的每个元素,若是最小元素,就让他带一个指向上一个最小元素的域,这样就很容易就实现了。

 

以下是代码

View Code
#pragma once

template 
<typename T>
class stack;

template 
<typename T>
class stack_node
{
    friend 
class stack<T>;
private:
    T data;
    
int smin; // 如果当前结点为最小结点,指向该结点压入前的最小结点位置
};

template 
<typename T>
class stack
{
public:
    stack(
int size = 10)
    {
        
this->size = size;
        a 
= new stack_node<T>[size];
        top 
= -1;
        min_index 
= -1;
    }

    
~stack()
    {
        delete[] a;
    }

    
bool is_empty()
    {
        
if (top == -1)
            
return true;
        
else
            
return false;
    }

    
bool is_full()
    {
        
if (top == size - 1)
            
return true;
        
else
            
return false;
    }

    T min()
    {
        
if (is_empty())
            
throw "stack is empty";
        
return a[min_index].data;
    }

    
void push(T data)
    {
        
if (is_full())
            
throw "stack is full";
        top 
++;
        a[top].data 
= data;
        
if (min_index == -1 || a[min_index].data > data)
        {
            a[top].smin 
= min_index;
            min_index 
= top;
        }
    }

    T pop()
    {
        
if (is_empty())
            
throw "stack is empty";
        
if (top == min_index)
            min_index 
= a[top].smin;
        
return a[top--].data;
    }

    T peek()
    {
        
if (is_empty())
            
throw "stack is empty";
        
return a[top];
    }

private:
    stack_node
<T> *a;
    
int top;
    
int min_index;
    
int size;
};

 

测试代码

View Code
#include "stack.h"
#include 
<iostream>

using namespace std;

int main()
{
    stack
<int> s(20);
    s.push(
10);
    cout
<<s.min()<<endl;
    s.push(
100);
    cout
<<s.min()<<endl;
    s.push(
3);
    cout
<<s.min()<<endl;
    s.push(
20);
    cout
<<s.min()<<endl;
    s.push(
17);
    cout
<<s.min()<<endl;
    s.pop();
    cout
<<s.min()<<endl;
    s.pop();
    cout
<<s.min()<<endl;
    s.pop();
    cout
<<s.min()<<endl;
    s.pop();
    cout
<<s.min()<<endl;
    
return 0;
}

 

posted on 2011-03-01 07:33  小橋流水  阅读(187)  评论(0编辑  收藏  举报

导航