218 StackUsingArrayC++
218 StackUsingArrayC++
class Stack{
private:
int size;
int top;
int* S;
public:
Stack(int size);
~Stack();
void push(int x);
int pop();
int peek(int index);
int isFull();
int isEmpty();
void display();
int stackTop();
};
Stack::Stack(int size) {
this->size = size;
top = -1;
S = new int[size];
}
Stack::~Stack() {
delete[] S;
}
void Stack::push(int x) {
if (isFull()){
cout << "Stack Overflow!" << endl;
} else {
top++;
S[top] = x;
}
}
int Stack::pop() {
int x = 1;
if (isEmpty()){
cout << "Stack Underflow!" << endl;
} else {
x = S[top];
top--;
}
return x;
}
int Stack::isEmpty() {
if (top == -1){
return 1;
}
return 0;
}
void Stack::display() {
for (int i=top; i>=0; i--){
cout << S[i] << " | " << flush;
}
cout << endl;
}
int Stack::stackTop() {
if (isEmpty()){
return -1;
}
return S[top];
}
int main() {
Stack stk(sizeof(A)/sizeof(A[0]));
// Display stack;
cout << "Stack: " << flush;
stk.display();
// Peek
cout << "Peek at 0th: " << stk.peek(0) << endl;
cout << "Peek at 3rd: " << stk.peek(3) << endl;
cout << "Peek at 10th: " << stk.peek(10) << endl;
// Top element
cout << "Top element: " << stk.stackTop() << endl;
return 0;
}