I am supposed to print the largest element of the stack (using vector to implement stack here) whenever i encounter a query "Q" it works just fine when i run it against some sample testcases but whenever i submit the code it gives me segmentation fault.
when the query is A 10 Add 10 to stack, when query is R pop element from stack, when query is Q print the largest element in the stack
#include <stdio.h>
#include <bits/stdc++.h>
#include <iostream>
#include <vector>
using namespace std;
int main() {
int t=0;
cin>>t;
for(int x=0;x<t;x++){
printf("Case %d:\n",x+1);
int q=0;
cin>>q;
vector<int> myvec;
vector<int> trackvec;
int top=-1;
for(int i=0;i<q;i++){
string s;
cin>>s;
if(s=="A"){
int num=0;
cin>>num;
myvec.push_back(num);
if(i==0){trackvec.push_back(num);top++;}
else{
if(num>trackvec[top]){
trackvec.push_back(num);
top++;
}
else{
trackvec.push_back(trackvec[top]);
top++;
}
}
}
else if(s=="R"){
myvec.pop_back();
trackvec.pop_back();
top--;
}
else if(s=="Q" && top==-1){
cout<<"Empty"<<endl;
}
else if(s=="Q"){
cout<<trackvec[top]<<endl;
}
}
}
}
The trackvec here is to keep track of the largest element
Sample input:
2
7
A 10
A 5
Q
A 100
Q
R
Q
6
A 5
Q
R
Q
R
R