-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMinElementInStack.cpp
More file actions
40 lines (35 loc) · 836 Bytes
/
MinElementInStack.cpp
File metadata and controls
40 lines (35 loc) · 836 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include<iostream>
#include <stack>
using namespace std;
int main(){
cout<<"Enter the size of stack"<<endl;
int n;
cin>>n;
int arr[n];
stack <int> mainStack, supportStack;
cout<<"Enter the elements of stack"<<endl;
for(int i = 0; i < n; i++){
cin>>arr[i];
mainStack.push(arr[i]);
}
//For Pushing
for(int i = 0; i < n; i++){
if(supportStack.size() == 0 || arr[i] <= supportStack.top() ){
supportStack.push( arr[i] );
}
}
//For Popping and getting Minimu Element at Each Pop
while(!mainStack.empty()){
if( mainStack.top() == supportStack.top() && !supportStack.empty() ){
mainStack.pop();
cout<<"Min element is "<<supportStack.top()<<endl;
supportStack.pop();
}
else
if(!supportStack.empty()){
mainStack.pop();
cout<<"Min element is "<<supportStack.top()<<endl;
}
}
return 0;
}