Implementation of Stack data structure using Array

Posted by 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


Implement Stack using Queue (using single queue)

Implementation of Queue data structure using Array

Implement Queue using Stack in amortized O(1) time

Find the next greater element for every element in an array

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