# LIFO Principle in Stack

Last Updated : 30 Nov, 2023

LIFO stands for “Last In, First Out“. This principle dictates that the last element added to the stack is the first one to be removed. In other words, the most recently added element is always at the top, and any operations on the stack will affect this top element.

## Use of LIFO principle in Stack:

### Push and Pop Operations:

• Push: Imagine you put an item on the top of your stack of plates. This is like “pushing” an item onto the stack in computer terms.
• Pop: When you take an item from the top of the stack, it’s like “popping” it off.

## Use Cases of LIFO Operation:

• Function Call Tracking: Stacks help computers remember what functions they’re doing. When you call a function, its details are pushed onto the stack. When the function finishes, its details are popped from the stack.
• Undo/Redo Functionality: We have undo and redo buttons in many apps, like text editors. Stacks help with this. When you do something, it’s pushed onto the stack. Undoing means popping the last action and redoing means pushing it back on.
• Expression Evaluation: Stacks are used for solving math problems with parentheses. When you read a math expression, you can use a stack to track what to do with numbers and symbols, making sure the last thing you put in is the first to be used.

## Example of LIFO in a Stack:

Let’s look at a simple example to illustrate the LIFO principle in a stack. We’ll perform a series of push and pop operations on a stack:

• Initially, the stack is empty.
• We push the elements A, B, and C onto the stack in that order.
• Stack: C, B, A
• Now, let’s pop an element from the stack. Since the LIFO principle is in effect, we will remove C, which is the most recently added element.
• Stack: B, A
• Next, we push D onto the stack.
• Stack: D, B, A
• Another pop operation removes D from the stack.
• Stack: B, A

As you can see, the last element added (D) was the first to be removed when we executed the pop operation. This is a clear demonstration of the LIFO principle at work.

The LIFO principle is a fundamental concept in computer science, and it plays a crucial role in how stacks operate. Understanding this principle is essential for designing and implementing algorithms and data structures that rely on stacks. Whether you’re working with function calls, expression evaluation, or any other stack-based operation, keeping the Last In, First Out principle in mind is key to success.