Design a stack that contains the Min function

Source: Internet
Author: User

Defines the data structure of the stack, requiring the addition of a min function to get the smallest element of the stack. The time complexity of the function min, pop and push is called O (1);

Method: A secondary stack is used to hold the smallest element. When the push operation is carried out, the smallest element in the stack is pushed into the secondary stack simultaneously, while the pop operation pops off the stack top element in the auxiliary stack. This is always the smallest element stored in the secondary stack corresponding to the position of the element stack.

#include <iostream> #include <stack>using namespace Std;template<class t>class stackwithmin{public: void push (const T value); void Pop (); T min ();p rivate:stack<t> datastack;stack<t> minstack;}; Template <class t>void stackwithmin<t>::p ush (T value) {Datastack.push (value); if (Minstack.size () ==0) { Minstack.push (value);} else if (Value<minstack.top ()) {Minstack.push (value);} Else{minstack.push (Minstack.top ());}} Template <class t>void Stackwithmin<t>::p op () {Datastack.pop (); Minstack.pop ();} Template <class t>t stackwithmin<t>::min () {T p;p=minstack.top (); return p;} int main () {int t; Stackwithmin<int> S;s.push (3); S.push (1); S.push (5); S.push (6); S.push (0); T=s.min ();cout<< "min:" < <t<<endl;s.pop (); T=s.min ();cout<< "min:" <<t<<endl;return 0;}

  

Design a stack that contains the Min function

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.