(试题)实现一个栈,要求实现Push(出栈)、Pop(入栈)、Min(返回最小值的操作)的时间复杂度为O(1)

思路分析

1、使用同一个栈,采取多次入栈出栈法
元素x入栈时,先push(x),然后push(min);
ps:min表示当前所在栈所有元素中的最小值
元素出栈时,则执行两次pop();

但此方法的不妥之处在于若入栈的元素数组为单调递增的,则每次需要push同一个值,此为操作冗余。

2、使用两个栈,比较入栈出栈法
使用两个栈s1、s2,s2用于压入最小值;
当元素x入栈时,将x与s2栈顶元素相比较,如果x

代码实现

template<class T>
class MinStack
{
public:
    MinStack()
    {}

    ~MinStack()
    {}

    void Push(const T& x)
    {
        if (s2.empty())
        {
            s1.push(x);
            s2.push(x);
        }
        else
        {
            if (x < s2.top())
                s2.push(x);
            s1.push(x);
        }

    }

    void Pop()
    {
        if (s2.empty())
        {
            return;
        }
        else
        {
            if (s1.top() == s2.top())
            {
                s2.pop();
            }
            s1.pop();
        }
    }

    T& Min()
    {
        if (!s2.empty())
        {
            return s2.top();
        }
    }

    void Print()
    {
        while (!s1.empty())
        {
            cout << s1.top() << ' ';
            s1.pop();
        }
        cout << endl;
    }

private:
    stack<T> s1;
    stack<T> s2;
};

测试用例

void Test3()
{
    MinStack<int> s1;
    s1.Push(1);
    s1.Push(2);
    s1.Push(3);
    s1.Push(4);
    s1.Push(5);


    s1.Pop();
    s1.Pop();
    s1.Pop();
    s1.Print();

    cout<<s1.Min();

}

实现结果

这里写图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个基本的顺序实现,包含入栈(push)和出栈(pop)操作。 ``` #include <stdio.h> #include <stdlib.h> #define MAXSIZE 100 // 定义的最大容量 typedef struct { int data[MAXSIZE]; // 存放中元素 int top; // 顶指针 } SqStack; // 初始化 void InitStack(SqStack *S) { S->top = -1; // 顶指针初始化为-1 } // 判断是否为空 int StackEmpty(SqStack S) { if (S.top == -1) { // 顶指针为-1,为空 return 1; } return 0; } // 判断是否已满 int StackFull(SqStack S) { if (S.top == MAXSIZE - 1) { // 顶指针等于最大容量减一,已满 return 1; } return 0; } // 入栈操作 int Push(SqStack *S, int x) { if (StackFull(*S)) { // 已满,无法入栈 return 0; } S->top++; // 顶指针加一 S->data[S->top] = x; // 将元素x入栈 return 1; } // 出栈操作 int Pop(SqStack *S, int *x) { if (StackEmpty(*S)) { // 为空,无法出栈 return 0; } *x = S->data[S->top]; // 将顶元素出栈 S->top--; // 顶指针减一 return 1; } int main() { SqStack S; int x; InitStack(&S); // 初始化 Push(&S, 1); // 入栈 Push(&S, 2); Push(&S, 3); Pop(&S, &x); // 出栈 printf("%d\n", x); // 输出出栈元素 Pop(&S, &x); printf("%d\n", x); Pop(&S, &x); printf("%d\n", x); Pop(&S, &x); // 尝试出栈 return 0; } ``` 需要注意的是,顶指针的初始值应该为-1,而不是0。在入栈操作时,先将顶指针加一,再将元素入栈;在出栈操作时,先将顶元素出栈,再将顶指针减一。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值