In this tutorial, we will learn how to implement a stack using an array in cpp. A stack is a linear data structure that follows the LIFO (Last In, First Out) principle. This means the last element inserted is the first one to be removed.
Operations :
- PUSH:- This operation is related to inserting an element onto the top of the stack.
- POP:- This operation is related to the deletion of an element from the top of the stack.
- TOP:- This operation is used to display the element at the top of the stack.
- EMPTY:- This operation is used to check whether the stack is empty or not
Code :
#include <iostream> using namespace std; #define n 100 class stack { int* arr; int top; public: stack() { arr = new int[n]; top = -1; } void push (int x) { if (top == n - 1) { cout << "stack overflow" << endl; return; } top++; arr[top] = x; cout <<"Element pushed to stack : "<< x <<endl; } int pop () { if (top == -1) { cout << "no elements to pop" << endl; } int x = arr[top]; top--; cout<<"Element popped from stack : "<< x <<endl; return x; } int Top () { if (top == -1) { cout << "stack is empty" << endl; return -1; } cout<<"Element at the top of stack : "<< arr[top] <<endl; return arr[top]; } bool empty () { return top == -1; } }; int main () { stack st; st.push (2); st.push (6); st.pop(); st.push (9); st.Top(); cout<<st.empty()<<endl; return 0; }
Explanation:
- The
Stack
class has two member variables:top
&arr
.top
: Index of the top element.arr
: Array to store elements.
- The
push()
function adds an element to the top of the stack. It increments thetop
before adding the element. - The
pop()
function removes and returns the top element of the stack. It decrementstop
after removing the element. - The
peek()
function returns the top element without removing it. - The
empty()
function checks whether the stack is empty or not.
Output:
Element pushed to stack : 2 Element pushed to stack : 6 Element popped from stack : 6 Element pushed to stack : 9 Element at the top of the stack : 9 0
Summary:
This implementation provides a basic understanding of stack operations using an array.