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

本文介绍了一种特殊栈的数据结构实现,此栈除了具备基本的push和pop操作外,还提供了一个min函数用于返回栈中当前的最小元素,且所有操作的时间复杂度均为O(1)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

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

 

以下是代码

ExpandedBlockStart.gifView 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;
};

 

测试代码

ExpandedBlockStart.gifView 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;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值