In the following code, I am getting the segmentation fault. Whenever the query type is 1, we have to push element into the stack, if it is 2 then we have to pop from stack, and if it is 3 then print the maximum value in the stack.
My guess is that the error is present somewhere in the switch case. However, I am unable to spot it. Please help.
#include<bits/stdc++.h>
using namespace std;
int maxinStack(stack<int> st){
int max=st.top();
for (int i=0;i<st.size();i++){
if(st.top()>max){
max=st.top();
}
st.pop();
}
return max;
}
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
stack<int> s;
int querySize;
cin >> querySize;
vector<int> queryType(querySize);
queue<int> queryData;
for(int i=0;i<querySize;i++){
cin>>queryType[i];
if(queryType[i]==1){
int x;
cin >> x;
queryData.push(x);
}
}
/*for (int j=0;j<querySize;j++){
cout << queryType.at(j)<<" ";
}
cout << endl;
while(!queryData.empty()){
cout << queryData.front()<<" ";
queryData.pop();
}
cout << endl;
*/
for (int j=0;j<querySize;j++){
switch (queryType[j]){
case 1:{
int y=queryData.front();
s.push(y);
queryData.pop();
}
case 2: s.pop();
case 3: cout << maxinStack(s)<<endl;
}
}
return 0;
}
Aucun commentaire:
Enregistrer un commentaire