Implementation of Stack data structure using Array

Posted by N.K. Chauhan on Mar 31, 2024

Implement a stack data structure using an array.

Note: A stack is a data structure that follows the LIFO (Last-In-First-Out) approach.


Solutions

Method 1: In O(n) time and O(n) space

Stack works on the principle of last in, first out, so we have to keep track of the most recently inserted element.

Initialize "top" as -1 and nsert an element in the array by increasing top by one (++top).

In order to pop(), check whether top is not equal to -1. If it is, return top and decrease its value by one (top--).

Complexity

The time complexity of this solution is O(n) and space complexity is O(n).

Related


Implementation of Queue data structure using Array

Find the next greater element for every element in a circular array

Implement Stack using Queue (using single queue)

Implement Queue using Stack in amortized O(1) time

Find the next greater element for every element in an array