I want to print the values in the stack in the order they were given as input, but after compiling, the stack is 2 4 7 5. Could anyone please help me?
stacktype.h
#ifndef STACKTYPE_H_INCLUDED
#define STACKTYPE_H_INCLUDED
const int MAX_ITEMS = 5;
class FullStack
// Exception class thrown
// by Push when stack is full.
{};
class EmptyStack
// Exception class thrown
// by Pop and Top when stack is emtpy.
{};
template <class ItemType>
class StackType
{
public:
StackType();
bool IsFull();
bool IsEmpty();
void Push(ItemType);
void Pop();
ItemType Top();
private:
int top;
ItemType items[MAX_ITEMS];
};
#endif // STACKTYPE_H_INCLUDED
stacktype.cpp
#include "StackType.h"
template <class ItemType>
StackType<ItemType>::StackType()
{
top = -1;
}
template <class ItemType>
bool StackType<ItemType>::IsEmpty()
{
return (top == -1);
}
template <class ItemType>
bool StackType<ItemType>::IsFull()
{
return (top == MAX_ITEMS-1);
}
template <class ItemType>
void StackType<ItemType>::Push(ItemType newItem)
{
if( IsFull() ) throw FullStack();
top++;
items[top] = newItem;
}
template <class ItemType>
void StackType<ItemType>::Pop()
{
if( IsEmpty() ) throw EmptyStack();
top--;
}
template <class ItemType>
ItemType StackType<ItemType>::Top()
{
if (IsEmpty()) throw EmptyStack();
return items[top];
}
main.cpp
#include <iostream>
#include "StackType.h"
#include "StackType.cpp"
using namespace std;
int main()
{
StackType<int> mystack;
if (mystack.IsEmpty()) {
cout << "Stack is Empty" << endl;
}
else {
cout << "Stack is Not Empty" << endl;
}
int stc[]={5, 7, 4, 2};
for(int i=0; i<4; i++)
{
mystack.Push(stc[i]);
}
if (mystack.IsEmpty()) {
cout << "Stack is Empty" << endl;
}
else {
cout << "Stack is Not Empty" << endl;
}
if (mystack.IsFull()) {
cout << "Stack is Full" << endl;
}
else {
cout << "Stack is Not Full" << endl;
}
for(int i=0; i<4; i++)
{
cout << mystack.Top() << " ";
mystack.Pop();
}
cout << endl;
[After compilation the stack looks 2 4 7 5 but I want to print the stack like 5 7 4 2][1]} [1]: https://i.stack.imgur.com/xyPXq.jpg