Created
January 22, 2016 22:59
-
-
Save karlding/089a1d1c5720e5c7c78d to your computer and use it in GitHub Desktop.
Stacks on stacks (implement a program that reads in push, pop, and inc operations, output the top of the stack at the end of each operation, prevent errors)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <stack> | |
#include <vector> | |
using namespace std; | |
int main() { | |
string s; | |
stack<int> st; | |
while (cin >> s) { | |
int i; | |
if (s == "push") { | |
cin >> i; | |
st.push(i); | |
} else if (s == "pop") { | |
if (!st.empty()) { | |
st.pop(); | |
} | |
} else if (s == "inc") { | |
int x, d; | |
cin >> x; | |
cin >> d; | |
// add d to the top x elements in the stack | |
stack<int> tmp; | |
while (!st.empty() && x > 0) { | |
tmp.push(st.top() + d); | |
st.pop(); | |
--x; | |
} | |
while (!tmp.empty()) { | |
st.push(tmp.top()); | |
tmp.pop(); | |
} | |
} | |
if (st.empty()) { | |
cout << "EMPTY" << endl; | |
} else { | |
cout << st.top() << endl; | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment