Any reason why my stack is displaying backwards??
That's how a stack works, it's a "last-in, first-out" structure. The item at the top will always be the last item that was pushed:
#include <iostream>
#include <stack>
int main()
{
using namespace std;
stack<int> st;
for (int i = 0; i < 5; ++i)
st.push(i);
// Display backward
while (!st.empty()) {
cout << st.top() << '\n';
st.pop();
}
}
To get the items in the order they were pushed you need a queue:
#include <iostream>
#include <queue>
int main()
{
using namespace std;
queue<int> q;
for (int i = 0; i < 5; ++i)
q.push(i);
// Display forward
while (!q.empty()) {
cout << q.front() << '\n';
q.pop();
}
}
Or you can figure out a way to reverse the stack. One way is to use two stacks:
#include <iostream>
#include <stack>
int main()
{
using namespace std;
stack<int> st;
for (int i = 0; i < 5; ++i)
st.push(i);
stack<int> temp;
// Display forward
while (!st.empty()) {
temp.push(st.top());
st.pop();
}
while (!temp.empty()) {
cout << temp.top() << '\n';
temp.pop();
}
}
Each item is popped from the reversed stack into the temporary stack. Reversing a reversed list gives you the forward list:
st:
|4|
|3| |3|
|2| |2| |2|
|1| |1| |1| |1|
|0| |0| |0| |0| |0|
temp:
|0|
|1| |1|
|2| |2| |2|
|3| |3| |3| |3|
|4| |4| |4| |4| |4|
Another way is to display the stack using recursion:
#include <iostream>
#include <stack>
namespace EdRules {
using namespace std;
void DisplayForward(stack<int> st)
{
if (st.empty())
return;
int temp = st.top();
st.pop();
DisplayForward(st);
cout << temp << '\n';
}
}
int main()
{
using namespace std;
stack<int> st;
for (int i = 0; i < 5; ++i)
st.push(i);
// Display forward
EdRules::DisplayForward(st);
}
This is exactly the same thing as using two stacks because recursion takes the place of the temporary stack.