Mark As Completed Discussion

Stack Operations

In this section, we will focus on implementing basic stack operations such as push, pop, and peek.

To begin, let's define the Stack class in C++ that will represent our stack data structure. The Stack class will have a fixed size and will use an array to store the elements.

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4const int MAX_SIZE = 100;
5
6class Stack {
7private:
8    int top;
9    int stack_array[MAX_SIZE];
10
11public:
12    Stack() {
13        top = -1;
14    }
15
16    bool is_empty() {
17        return (top == -1);
18    }
19
20    bool is_full() {
21        return (top == MAX_SIZE - 1);
22    }
23
24    void push(int value) {
25        if (is_full()) {
26            cout << "Stack overflow!" << endl;
27            return;
28        }
29
30        stack_array[++top] = value;
31    }
32
33    int pop() {
34        if (is_empty()) {
35            cout << "Stack underflow!" << endl;
36            return -1;
37        }
38
39        return stack_array[top--];
40    }
41
42    int peek() {
43        if (is_empty()) {
44            cout << "Stack is empty!" << endl;
45            return -1;
46        }
47
48        return stack_array[top];
49    }
50};
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment