What is a Stack? LIFO in Stack and Real World Applications written by Nischal Lal Shrestha.
Image of Nischal who is author of the post.

By Nischal Lal Shrestha

On Thu 12 April 2018

What is a Stack? LIFO in Stack and Real World Applications

What is a Stack?

Stack is a linear data structure where the addition of new items and the removal of existing items always takes place at the same end. This end is commonly called as "top". As all the addition and removal in a stack is done from the "top" of the stack, the item added most recently will be removed first. Hence stack is called Last-In-First-Out(LIFO) data structure.

Analogy for Stack

Let's explore the concepts of Stack using an analogy. You must have seen a pile of plates where one plate is placed on top of another. Now, when you have to remove a plate, you remove the topmost plate first. When you want to add a plate, you have to add the plate on the top of the pile. This is Stack. Beside this, there are many examples of stacks that occurs daily. The stock of book you see on your study desk is also a stack.

Operations on a Stack

A Stack data type can be defined by push, pop, and peek operations. The push operation adds a new item to the top of the stacks. The pop operations removes the top item from the stack and the peek operation return the top item from the stack but doesn't delete it.

Push Operation

The push operation is used to add a element to the top of the stack. It needs an item**(which will be inserted in stack) and returns nothing. However, before inserting the **item, we must check whether the stack is full or not. If the stack is full no insertions can be done and a STACKOVERFLOW message is printed.

Pop Operation

The pop operation removes the topmost element from the stack. It returns the item which is deleted. However, before deleting the item, we must first check if the Stack is Empty or not. If it is empty there will be nothing to delete so STACKUNDERFLOW message is printed.

Peek Operation

The peek operation returns the top item from the stack but doesn't delete it. As with the pop operation we must first check if the stack is empty or not. If empty nothing can be peeked so an appropriate message should be printed.

Applications of Stack