Open In App

LIFO (Last-In-First-Out) approach in Programming

Last Updated : 01 Sep, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Prerequisites – FIFO (First-In-First-Out) approach in Programming, FIFO vs LIFO approach in Programming 
LIFO is an abbreviation for last in, first out. It is a method for handling data structures where the first element is processed last and the last element is processed first.

Real-life example:

In this example, following things are to be considered: 

  • There is a bucket that holds balls.
  • Different types of balls are entered into the bucket.
  • The ball to enter the bucket last will be taken out first.
  • The ball entering the bucket next to last will be taken out after the ball above it (the newer one).
  • In this way, the ball entering the bucket first will leave the bucket last.
  • Therefore, the Last ball (Blue) to enter the bucket gets removed first and the First ball (Red) to enter the bucket gets removed last.

This is known as Last-In-First-Out approach or LIFO.

Where is LIFO used:

  1. Data Structures:
    Certain data structures like Stacks and other variants of Stacks use LIFO approach for processing data.
  2. Extracting latest information:
    Sometimes computers use LIFO when data is extracted from an array or data buffer. When it is required to get the most recent information entered, the LIFO approach is used.  

Program Examples for LIFO:

Implementation: Using Stack data structure.

C++




// C++ program to demonstrate
// working of LIFO
// using stack in C++
#include<bits/stdc++.h>
using namespace std;
 
// Pushing element on the top of the stack
stack<int> stack_push(stack<int> stack)
{
    for (int i = 0; i < 5; i++)
    {
        stack.push(i);
    }
    return stack;
}
 
// Popping element from the top of the stack
stack<int> stack_pop(stack<int> stack)
{
    cout << "Pop :";
 
    for (int i = 0; i < 5; i++)
    {
        int y = (int)stack.top();
        stack.pop();
        cout << (y) << endl;
    }
    return stack;
}
 
// Displaying element on the top of the stack
void stack_peek(stack<int> stack)
{
    int element = (int)stack.top();
    cout << "Element on stack top : " << element << endl;
}
 
// Searching element in the stack
void stack_search(stack<int> stack, int element)
{
    int pos = -1,co = 0;
    while(stack.size() > 0)
    {
        co++;
        if(stack.top() == element)
        {
            pos = co;
            break;
        }
        stack.pop();
    }
 
    if (pos == -1)
        cout << "Element not found" << endl;
    else
        cout << "Element is found at position " << pos << endl;
}
 
// Driver code
int main()
{
    stack<int> stack ;
 
    stack = stack_push(stack);
    stack = stack_pop(stack);
    stack = stack_push(stack);
    stack_peek(stack);
    stack_search(stack, 2);
    stack_search(stack, 6);
    return 0;
}
     
// This code is contributed by Arnab Kundu


Java




// 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);
    }
}


Python3




# Python3 program to demonstrate working of LIFO
 
# Pushing element on the top of the stack
def stack_push(stack):
    for i in range(5):
        stack.append(i)
    return stack
  
# Popping element from the top of the stack
def stack_pop(stack):
    print("Pop :")
  
    for i in range(5):
        y = stack[-1]
        stack.pop()
        print(y)
    return stack
  
# Displaying element on the top of the stack
def stack_peek(stack):
    element = stack[-1]
    print("Element on stack top :", element)
  
# Searching element in the stack
def stack_search(stack, element):
    pos = -1
    co = 0
    while(len(stack) > 0):
        co+=1
        if(stack[-1] == element):
            pos = co
            break
        stack.pop()
  
    if (pos == -1):
        print( "Element not found")
    else:
        print("Element is found at position", pos)
 
stack = []
stack_push(stack)
stack_pop(stack)
stack_push(stack)
stack_peek(stack)
stack_search(stack, 2)
stack_search(stack, 6)
 
# This code is contributed by rameshtravel07.


C#




// C# program to demonstrate
// working of LIFO
// using Stack in C#
using System;
using System.Collections.Generic;
 
class GFG
{
    // Pushing element on the top of the stack
    static void stack_push(Stack<int> stack)
    {
        for (int i = 0; i < 5; i++)
        {
            stack.Push(i);
        }
    }
 
    // Popping element from the top of the stack
    static void stack_pop(Stack<int> stack)
    {
        Console.WriteLine("Pop :");
 
        for (int i = 0; i < 5; i++)
        {
            int y = (int)stack.Pop();
            Console.WriteLine(y);
        }
    }
 
    // Displaying element on the top of the stack
    static void stack_peek(Stack<int> stack)
    {
        int element = (int)stack.Peek();
        Console.WriteLine("Element on stack top : " + element);
    }
 
    // Searching element in the stack
    static void stack_search(Stack<int> stack, int element)
    {
        bool pos = stack.Contains(element);
 
        if (pos == false)
            Console.WriteLine("Element not found");
        else
            Console.WriteLine("Element is found at position " + pos);
    }
 
    // Driver code
    public static void Main(String[] args)
    {
        Stack<int> stack = new Stack<int>();
 
        stack_push(stack);
        stack_pop(stack);
        stack_push(stack);
        stack_peek(stack);
        stack_search(stack, 2);
        stack_search(stack, 6);
    }
}
 
// This code contributed by Rajput-Ji


Javascript




<script>
 
// JavaScript program to demonstrate
// working of LIFO
 
 
// Pushing element on the top of the stack
function stack_push(stack)
{
    for (var i = 0; i < 5; i++)
    {
        stack.push(i);
    }
    return stack;
}
 
// Popping element from the top of the stack
function stack_pop(stack)
{
    document.write(  "Pop :<br>");
 
    for (var i = 0; i < 5; i++)
    {
        var y = parseInt(stack[stack.length-1]);
        stack.pop();
        document.write( y + "<br>");
    }
    return stack;
}
 
// Displaying element on the top of the stack
function stack_peek(stack)
{
    var element = parseInt(stack[stack.length-1]);
    document.write( "Element on stack top : " + element +
    "<br>");
}
 
// Searching element in the stack
function stack_search( stack,  element)
{
    var pos = -1,co = 0;
    while(stack.length > 0)
    {
        co++;
        if(stack[stack.length-1] == element)
        {
            pos = co;
            break;
        }
        stack.pop();
    }
 
    if (pos == -1)
        document.write( "Element not found" + "<br>");
    else
        document.write("Element is found at position "
        + pos + "<br>");
}
 
    stack=[] ;
 
    stack = stack_push(stack);
    stack = stack_pop(stack);
    stack = stack_push(stack);
    stack_peek(stack);
    stack_search(stack, 2);
    stack_search(stack, 6);
 
     
// This code is contributed by SoumikMondal
 
</script>


Output

Pop :4
3
2
1
0
Element on stack top : 4
Element is found at position 3
Element not found

Complexity Analysis:

  • Time Complexity: O(n)
  • Auxiliary Space: O(n) 


Similar Reads

FIFO vs LIFO approach in Programming
FIFO is an abbreviation for first in, first out. It is a method for handling data structures where the first element is processed first and the newest element is processed last. Prerequisite - FIFO (First-In-First-Out) approach in Programming Real-life example: LIFO is an abbreviation for Last in, first out is the same as first in, last out (FILO).
2 min read
FIFO (First-In-First-Out) approach in Programming
FIFO is an abbreviation for first in, first out. It is a method for handling data structures where the first element is processed first and the newest element is processed last. Real-life example: In this example, following things are to be considered: There is a ticket counter where people come, take tickets and go.People enter a line (queue) to g
5 min read
LIFO Principle in Stack
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 ite
3 min read
Print the last k nodes of the linked list in reverse order | Recursive approach
Given a linked list containing N nodes and a positive integer k should be less than or equal to N. The task is to print the last k nodes of the list in reverse order. Examples: Input: list: 1-&gt;2-&gt;3-&gt;4-&gt;5, k = 2 Output: 5 4 Input: list: 3-&gt;10-&gt;6-&gt;9-&gt;12-&gt;2-&gt;8, k = 4 Output: 8 2 12 9 Source: Amazon Interview Experience SD
7 min read
Count distinct sequences obtained by replacing all elements of subarrays having equal first and last elements with the first element any number of times
Given an array arr[] consisting of N integers, the task is to find the number of different sequences that can be formed after performing the below operation on the given array arr[] any number of times. Choose two indices i and j such that arr[i] is equal to arr[j] and update all the elements in the range [i, j] in the array to arr[i]. Examples: In
7 min read
Find out the person who got the ticket last.
N people from 1 to N are standing in the queue at a movie ticket counter. It is a weird counter, as it distributes tickets to the first K people and then the last K people and again the first K people, and so on, once a person gets a ticket moves out of the queue. The task is to find the last person to get the ticket. Examples: Input: N = 9, K = 3O
14 min read
Longest subsequence with a given OR value : Dynamic Programming Approach
Given an array arr[], the task is to find the longest subsequence with a given OR value M. If there is no such sub-sequence then print 0.Examples: Input: arr[] = {3, 7, 2, 3}, M = 3 Output: 3 {3, 2, 3} is the required subsequence 3 | 2 | 3 = 3Input: arr[] = {2, 2}, M = 3 Output: 0 Approach: A simple solution is to generate all the possible sub-sequ
6 min read
A Better Way To Approach Competitive Programming
This article helps to all those who want to begin with Competitive Programming. The only prerequisite one need is the knowledge of a programming language. Now, Let us find a better approach to Competitive Programming. Please note: One should read the proper Input and Output format because most of the beginners make mistakes of having extra print st
4 min read
Greedy Approach vs Dynamic programming
Greedy approach and Dynamic programming are two different algorithmic approaches that can be used to solve optimization problems. Here are the main differences between these two approaches: Greedy Approach:The greedy approach makes the best choice at each step with the hope of finding a global optimum solution.It selects the locally optimal solutio
2 min read
Queue based approach for first non-repeating character in a stream
Given a stream of characters and we have to find first non repeating character each time a character is inserted to the stream. Examples: Input : a a b c Output : a -1 b b Input : a a c Output : a -1 cRecommended PracticeFirst non-repeating character in a streamTry It! We have already discussed a Doubly linked list based approach in the previous po
5 min read
Practice Tags :
three90RightbarBannerImg