LIFO stands for Last In,First Out. It is a way of processing data in which the last element entered will be first to be served or processed. LIFO is quite opposite to FIFO.
Real Life Example:
- Imagine a stack of cards containing one card on top of another, starting from the bottom.
- When we remove a card we take out the top card first which has been added to the stack last/recently.
- Then we remove the next card.
- Similarly, the last card present in the stack of cards is the first card to enter the stack.
This is known ad LIFO approach.
Last in, First out system of approach is used in :-
- Data Structures: There are data structures like stack and other variants of stack where we use LIFO system for processing the data.
- Extracting Latest Information:
Computers use LIFO when data needs to be extracted from an array or data buffer. To get the most recent information entered, the LIFO system is used.
Program example foe LIFO implementation in Stacks:
// Java program to demonstrate
// working of LIFO
// using Stack in Java
import java.io.*;
import java.util.*;
class GFG {
// Pushing element on the top of the stack
static void stack_push(Stack<Integer> stack)
{
for (int i = 0; i < 5; i++) {
stack.push(i);
}
}
// Popping element from the top of the stack
static void stack_pop(Stack<Integer> stack)
{
System.out.println("Pop :");
for (int i = 0; i < 5; i++) {
Integer y = (Integer)stack.pop();
System.out.println(y);
}
}
// Displaying element on the top of the stack
static void stack_peek(Stack<Integer> stack)
{
Integer element = (Integer)stack.peek();
System.out.println("Element on stack top : " + element);
}
// Searching element in the stack
static void stack_search(Stack<Integer> stack, int element)
{
Integer pos = (Integer)stack.search(element);
if (pos == -1)
System.out.println("Element not found");
else
System.out.println("Element is found at position " + pos);
}
public static void main(String[] args)
{
Stack<Integer> stack = new Stack<Integer>();
stack_push(stack);
stack_pop(stack);
stack_push(stack);
stack_peek(stack);
stack_search(stack, 2);
stack_search(stack, 6);
}
} Output:
Pop:
4
3
2
1
0
Element on stack top : 4
Element is found at position 3
Element not found
Contributed by Shyam Kumar With 💜.
Reach me on
