Stack implementation in Java

A stack is a linear data structure which 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 as top.


 

The stack supports below core operations –

  • push Pushes an item onto 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 number of elements present in the stack.
     

Stack can easily be implemented as array. Below is the Stack implementation in Java using an array.

 

Download   Run Code

Output:

Inserting 1
Inserting 2
Removing 2
Removing 1
Inserting 3
Top element is: 3
Stack size is 1
Removing 3
Stack Is Empty

 

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

 


 

Stack is also included in Java’s collection framework.

 

Download   Run Code

Output:

Top element is: D
Stack size is 2
Stack is not Empty

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz