I have fixed the code for you
#include <iostream>
using namespace std;
int n=100;
class stAck
{
enum
{
SIZE = 100,
EMPTY = -1
};
int * arr;
int tp;
public:
stAck()
{
arr = new int[SIZE];
tp = EMPTY;
}
~stAck()
{
delete [] arr;
}
void push(int x)
{
if (tp == (SIZE-1))
{
cout<<" Stack overflow"<<endl; return;
}
tp++;
arr[tp]=x;
}
bool empty()
{
return ( tp == EMPTY);
}
void pop()
{
if ( empty() )
{
cout<<"no elements to be popped"<<endl;
return;
}
tp--;
}
int top()
{
if ( empty() )
{
cout<<"no item at the top of the empty stack" << endl;
return EMPTY;
}
return arr[tp];
}
};
int main()
{
stAck st;
st.push(1);
st.push(2);
st.push(3);
cout << st.top() << endl;
st.pop();
st.pop();
cout<<st.empty()<<endl;
st.pop();
cout<<st.empty()<<endl;
}
You may also write
#include <iostream>
using namespace std;
template <size_t N>
class stAck
{
enum
{
EMPTY = -1
};
int arr[N];
int tp;
public:
stAck()
{
tp = EMPTY;
}
void push(int x)
{
if (tp == (N-1))
{
cout << " Stack overflow" << endl;
return;
}
tp++;
arr[tp] = x;
}
bool empty()
{
return ( tp == EMPTY);
}
void pop()
{
if ( empty() )
{
cout<<"no elements to be popped"<<endl;
return;
}
tp--;
}
int top()
{
if ( empty() )
{
cout<<"no item at the top of the empty stack" << endl;
return EMPTY;
}
return arr[tp];
}
};
int main()
{
stAck<5> st;
st.push(1);
st.push(2);
st.push(3);
cout << st.top() << endl;
st.pop();
st.pop();
cout<<st.empty()<<endl;
st.pop();
cout<<st.empty()<<endl;
}
Or, even better, use the
stack
class provided by the
C++
standard library
#include <iostream>
#include <stack>
using namespace std;
int main()
{
stack<int> st;
st.push(1);
st.push(2);
st.push(3);
cout << st.top() << endl;
st.pop();
st.pop();
cout<<st.empty()<<endl;
st.pop();
cout<<st.empty()<<endl;
}