current position:Home>155. Minimum stack (c + + problem solution, including vs runnable source program)

155. Minimum stack (c + + problem solution, including vs runnable source program)

2022-01-27 04:37:28 Bufan

155. Smallest stack (C++ Problem solution contains VS Can run the source program )

1. Answer key

Auxiliary stack

Use the auxiliary stack : Two auxiliary stacks ( A data stack , A minimum stack )

2. Power button C++ Source code

class MinStack {
    
public:
    MinStack() {
    

    }
    
    void push(int val) {
    
        s1.push(val);
        if (minS.empty() || minS.top() >= val) {
    
            minS.push(val);
        }
    }

    void pop() {
    
        if (minS.top() == s1.top())
            minS.pop();
        s1.pop();
    }

    int top() {
    
        return s1.top();
    }

    int getMin() {
    
        return minS.top();
    }
    // Use the auxiliary stack 
    stack<int> s1, minS;
};

/** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */

3.VS Can run the source program

#include<stdio.h>
#include<stdlib.h>
#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<limits>
#include<algorithm>
#include<math.h>
#pragma warning(disable:4996)
using namespace std;

// Use the auxiliary stack : Two auxiliary stacks ( A data stack , A minimum stack )
class MinStack {
    
public:
    MinStack() {
    

    }

    void push(int val) {
    
        s1.push(val);
        if (minS.empty() || minS.top() >= val) {
    
            minS.push(val);
        }
    }

    void pop() {
    
        if (minS.top() == s1.top())
            minS.pop();
        s1.pop();
    }

    int top() {
    
        return s1.top();
    }

    int getMin() {
    
        return minS.top();
    }
    // Use the auxiliary stack 
    stack<int> s1, minS;
};

/** * Your MinStack object will be instantiated and called as such: * MinStack* obj = new MinStack(); * obj->push(val); * obj->pop(); * int param_3 = obj->top(); * int param_4 = obj->getMin(); */
int main()
{
    
    MinStack* obj = new MinStack();
    obj->push(-2);
    obj->push(0);
    obj->push(-3);
    printf(" At this time, the minimum value in the stack is :%d\n", obj->getMin());
    obj->pop();
    printf(" At this point, the top element of the stack is :%d\n", obj->top());
    printf(" At this time, the minimum value in the stack is :%d", obj->getMin());

	printf("\n");
	system("pause");
	return 0;
}

copyright notice
author[Bufan],Please bring the original link to reprint, thank you.
https://en.cdmana.com/2022/01/202201270437230514.html

Random recommended