Seeking the minimum data stack

Description Title:
  implement a special stack, to achieve the basic functions on the stack, then the return stack to achieve the minimum operating elements.
  [Requirements]
  1. time complexity pop, push, getMin operations are O (1).
  2. Stack type of design can use ready-made stack structure.


Problem-solving ideas:
  the use of an auxiliary stack, the minimum stack currently kept inside

 

Code:  

  

. 1  class GetMin
 2  {
 . 3  public :
 . 4      void PushData ( int A)
 . 5      {
 . 6          Data.push (A);
 . 7          IF (Min.empty ())
 . 8              Min.push (A); // when the number has not been stored , the minimum value of the current stack is the first number 
. 9          the else 
10              Min.push (Min.top () <= a? Min.top (): a);
 . 11          // new stack is added to the number of minimum compared value, stored in the new minimum, in order to maintain the height of the stack as Min and Data 
12 is      }
 13 is  
14      int getTop ()
 15      {
 16          IF(Data.size())
17             return Data.top();
18         return -1;
19     }
20 
21     int theMin()
22     {
23         if (Data.size())
24             return Min.top();
25         return -1;
26     }
27 
28     void PopData()
29     {
30         if (Data.size())
31         {
32             Data.pop();
33             Min.pop();
34         }
35     }
36 
37 private:
38     stack<int>Data;
39     stack<int>Min;
40 };
41 
42 void Test()
43 {
44     GetMin ss;
45     ss.PushData(6);
46     cout << ss.theMin() << endl;
47     ss.PushData(5);
48     cout << ss.theMin() << endl;
49     ss.PushData(2);
50     cout << ss.theMin() << endl;
51     ss.PushData(1);
52     cout << ss.theMin() << endl;
53     ss.PushData(3);
54     cout << ss.theMin() << endl;
55     ss.PushData(6);
56     cout << ss.theMin() << endl;
57 
58     ss.PopData(); 
59     cout << ss.theMin() << endl;
60     ss.PopData();
61     cout << ss.theMin() << endl;
62     ss.PopData();
63     cout << ss.theMin() << endl;
64     ss.PopData();
65     cout << ss.theMin() << endl;
66 
67 }

 

Guess you like

Origin www.cnblogs.com/zzw1024/p/10988060.html