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   小橋流水  阅读(192)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· [AI/GPT/综述] AI Agent的设计模式综述

导航

统计

点击右上角即可分享
微信分享提示