A stack is a linear data structure that follows the LIFO (Last–In, First–Out) principle. That means the objects can be inserted or removed only at one end of it, also called a top.

The stack supports the following operations:

  • push inserts an item at the top of the stack (i.e., above its current top element).
  • pop removes the object at the top of the stack and returns that object from the function. The stack size will be decremented by one.

    Data stack
  • isEmpty tests if the stack is empty or not.
  • isFull tests if the stack is full or not.
  • peek returns the object at the top of the stack without removing it from the stack or modifying the stack in any way.
  • size returns the total number of elements present in the stack.

Practice this problem

Stack Implementation using an array

A stack can easily be implemented as an array. Following is the stack implementation in Java using an array:

Download  Run Code


Output:
 
Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
The top element is 3
The stack size is 1
Removing 3
The stack is empty

 
The time complexity of push(), pop(), peek(), isEmpty(), isFull() and size() is constant, i.e., O(1).

Using Java Collections

The stack is also included in Java’s collection framework.

Download  Run Code


Output:
 
The top element is D
The stack size is 2
The stack is not empty

 
Also See:

Stack Implementation in C

Stack Implementation in C++

Stack Implementation in Python

Stack Implementation using a Linked List – C, Java, and Python