#include <iostream> using namespace std; class Stack { public: int *arr; // properties int top; int size; // constructor Stack(int size) { this->size = size; arr = new int[size]; top = -1; } // push function void push(int element) { if (size - top > 1) { // Check for empty space top++; arr[top] = element; } else { cout << "Stack overflow" << endl; } } // pop function void pop() { if (top >= 0) { top--; } else { cout << "Stack underflow" << endl; } } // peek function int peek() { if (top >= 0) { return arr[top]; } else { cout << "Stack is empty" << endl; return -1; } } // isEmpty function bool isEmpty() { return top == -1; } // delete stack function void deleteStack() { delete[] arr; // Free the allocated memory arr = nullptr; // Reset the pointer top = -1; // Reset the top size = 0; // Reset the size cout << "Stack has been deleted" << endl; } }; int main() { Stack st(5); st.push(20); st.push(30); st.push(50); cout << "Top element before deletion: " << st.peek() << endl; st.deleteStack(); // After deletion, trying to access the stack if (st.arr == nullptr) { cout << "Stack array is nullptr after deletion." << endl; } return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter