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.
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.
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.
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
Stack can be used to reverse a word.
"undo" operations in text editors and word processors is accomplished by keeping all the text changes in a stack.
Hey there, I'm Nischal.
I am a student, a developer and I specialize in
standards-based Django, JS, HTML, CSS web development.
I love Everything that makes me more Human. While
not Coding, I play and/or watch football.