代码比较简单,测试都懒得了,这个问题思想是精华。
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 #include<iostream>
2 using namespace std;
3
4 class Stack
5 {
6 private:
7 int *elements;
8 int top;
9 int maxSize;
10
11 public:
12 Stack(int sz=50):top(-1),maxSize(sz)
13 {
14 elements=new int[maxSize];
15 }
16
17 void push(int x)
18 {
19 elements[++top]=x;
20 }
21
22 int pop()
23 {
24 top--;
25 return elements[top+1];
26 }
27
28 int peek()
29 {
30 return elements[top];
31 }
32
33 bool isEmpty()
34 {
35 return (top==-1)?true:false;
36 }
37 };
38
39 class NewStack1
40 {
41 private:
42 Stack dataStack;
43 Stack minStack;
44 public:
45 NewStack1()
46 {
47 }
48 void push(int x)
49 {
50 dataStack.push(x);
51 if(minStack.isEmpty())
52 minStack.push(x);
53 if(x>minStack.peek())
54 minStack.push(minStack.peek());
55 else
56 minStack.push(x);
57 }
58 int pop()
59 {
60 if(dataStack.isEmpty())
61 {
62 cout<<"pop出错,栈为空!"<<endl;
63 }
64 minStack.pop();
65 return dataStack.pop();
66 }
67 int min()
68 {
69 if(dataStack.isEmpty())
70 {
71 cout<<"pop出错,栈为空!"<<endl;
72 }
73 return minStack.peek();
74 }
75 };
76
77 class NewStack2
78 {
79 private:
80 Stack stack;
81 public:
82 NewStack2()
83 {
84 }
85
86 void push(int x)
87 {
88 if(stack.isEmpty())
89 {
90 stack.push(x);
91 stack.push(x);
92 }
93 if(x>stack.peek())
94 {
95 int min=stack.peek();
96 stack.push(x);
97 stack.push(min);
98 }
99 else
100 {
101 stack.push(x);
102 stack.push(x);
103 }
104 }
105
106 int pop()
107 {
108 stack.pop();
109 return stack.pop();
110 }
111
112 int min()
113 {
114 return stack.peek();
115 }
116 };