First Fit algorithm in Memory Management using Linked List
Last Updated :
15 Jul, 2025
First Fit Algorithm for Memory Management: The first memory partition which is sufficient to accommodate the process is allocated.
We have already discussed first fit algorithm using arrays in this article. However, here we are going to look into another approach using a linked list where the deletion of allocated nodes is also possible.
Examples:
Input: blockSize[] = {100, 500, 200}
processSize[] = {417, 112, 426, 95}
Output:
Block of size 426 can't be allocated
Tag Block ID Size
0 1 417
1 2 112
2 0 95
After deleting block with tag id 0.
Tag Block ID Size
1 2 112
2 0 95
3 1 426

Approach: The idea is to use the memory block with a unique tag id. Each process of different sizes are given block id, which signifies to which memory block they belong to, and unique tag id to delete particular process to free up space. Create a free list of given memory block sizes and allocated list of processes.
Create allocated list:
Create an allocated list of given process sizes by finding the first memory block with sufficient size to allocate memory from. If the memory block is not found, then simply print it. Otherwise, create a node and add it to the allocated linked list.
Delete process:
Each process is given a unique tag id. Delete the process node from the allocated linked list to free up some space for other processes. After deleting, use the block id of the deleted node to increase the memory block size in the free list.
Below is the implementation of the approach:
C++
// C++ implementation of the First
// sit memory management algorithm
// using linked list
#include <bits/stdc++.h>
using namespace std;
// Two global counters
int g = 0, k = 0;
// Structure for free list
struct free {
int tag;
int size;
struct free* next;
}* free_head = NULL, *prev_free = NULL;
// Structure for allocated list
struct alloc {
int block_id;
int tag;
int size;
struct alloc* next;
}* alloc_head = NULL, *prev_alloc = NULL;
// Function to create free
// list with given sizes
void create_free(int c)
{
struct free* p
= (struct free*)malloc(sizeof(struct free));
p->size = c;
p->tag = g;
p->next = NULL;
if (free_head == NULL)
free_head = p;
else
prev_free->next = p;
prev_free = p;
g++;
}
// Function to print free list which
// prints free blocks of given sizes
void print_free()
{
struct free* p = free_head;
cout << "Tag\tSize\n";
while (p != NULL) {
cout << p->tag << "\t" << p->size << "\n";
p = p->next;
}
}
// Function to print allocated list which
// prints allocated blocks and their block ids
void print_alloc()
{
struct alloc* p = alloc_head;
cout << "Tag\tBlock ID\tSize\n";
while (p != NULL) {
cout << p->tag << "\t " << p->block_id << "\t\t"
<< p->size << "\n";
p = p->next;
}
}
// Function to allocate memory to
// blocks as per First fit algorithm
void create_alloc(int c)
{
// create node for process of given size
struct alloc* q
= (struct alloc*)malloc(sizeof(struct alloc));
q->size = c;
q->tag = k;
q->next = NULL;
struct free* p = free_head;
// Iterate to find first memory
// block with appropriate size
while (p != NULL) {
if (q->size <= p->size)
break;
p = p->next;
}
// Node found to allocate
if (p != NULL) {
// Adding node to allocated list
q->block_id = p->tag;
p->size -= q->size;
if (alloc_head == NULL)
alloc_head = q;
else {
prev_alloc = alloc_head;
while (prev_alloc->next != NULL)
prev_alloc = prev_alloc->next;
prev_alloc->next = q;
}
k++;
}
else // Node found to allocate space from
cout << "Block of size " << c
<< " can't be allocated\n";
}
// Function to delete node from
// allocated list to free some space
void delete_alloc(int t)
{
// Standard delete function
// of a linked list node
struct alloc *p = alloc_head, *q = NULL;
// First, find the node according
// to given tag id
while (p != NULL) {
if (p->tag == t)
break;
q = p;
p = p->next;
}
if (p == NULL)
cout << "Tag ID doesn't exist\n";
else if (p == alloc_head)
alloc_head = alloc_head->next;
else
q->next = p->next;
struct free* temp = free_head;
while (temp != NULL) {
if (temp->tag == p->block_id) {
temp->size += p->size;
break;
}
temp = temp->next;
}
}
// Driver Code
int main()
{
int blockSize[] = { 100, 500, 200 };
int processSize[] = { 417, 112, 426, 95 };
int m = sizeof(blockSize) / sizeof(blockSize[0]);
int n = sizeof(processSize) / sizeof(processSize[0]);
for (int i = 0; i < m; i++)
create_free(blockSize[i]);
for (int i = 0; i < n; i++)
create_alloc(processSize[i]);
print_alloc();
// Block of tag id 0 deleted
// to free space for block of size 426
delete_alloc(0);
create_alloc(426);
cout << "After deleting block"
<< " with tag id 0.\n";
print_alloc();
}
Java
// Java implementation of the First
// sit memory management algorithm
// using linked list
public class GFG {
// Two global counters
static int g = 0, k = 0;
// Structure for free list
static class free {
int tag;
int size;
free next;
}
static free free_head = null;
static free prev_free = null;
// Structure for allocated list
static class alloc {
int block_id;
int tag;
int size;
alloc next;
}
static alloc alloc_head = null;
static alloc prev_alloc = null;
// Function to create free
// list with given sizes
static void create_free(int c)
{
free p = new free();
p.size = c;
p.tag = g;
p.next = null;
if (free_head == null)
free_head = p;
else
prev_free.next = p;
prev_free = p;
g++;
}
// Function to print free list which
// prints free blocks of given sizes
static void print_free()
{
free p = free_head;
System.out.println("Tag\tSize");
while (p != null) {
System.out.println(p.tag + "\t" + p.size);
p = p.next;
}
}
// Function to print allocated list which
// prints allocated blocks and their block ids
static void print_alloc()
{
alloc p = alloc_head;
System.out.println("Tag\tBlock ID\tSize");
while (p != null) {
System.out.println(p.tag + "\t " + p.block_id
+ "\t\t" + p.size);
p = p.next;
}
}
// Function to allocate memory to
// blocks as per First fit algorithm
static void create_alloc(int c)
{
// create node for process of given size
alloc q = new alloc();
q.size = c;
q.tag = k;
q.next = null;
free p = free_head;
// Iterate to find first memory
// block with appropriate size
while (p != null) {
if (q.size <= p.size)
break;
p = p.next;
}
// Node found to allocate
if (p != null) {
// Adding node to allocated list
q.block_id = p.tag;
p.size -= q.size;
if (alloc_head == null)
alloc_head = q;
else {
prev_alloc = alloc_head;
while (prev_alloc.next != null)
prev_alloc = prev_alloc.next;
prev_alloc.next = q;
}
k++;
}
else // Node found to allocate space from
System.out.println("Block of size " + c
+ " can't be allocated");
}
// Function to delete node from
// allocated list to free some space
static void delete_alloc(int t)
{
// Standard delete function
// of a linked list node
alloc p = alloc_head, q = null;
// First, find the node according
// to given tag id
while (p != null) {
if (p.tag == t)
break;
q = p;
p = p.next;
}
if (p == null)
System.out.println("Tag ID doesn't exist");
else if (p == alloc_head)
alloc_head = alloc_head.next;
else
q.next = p.next;
free temp = free_head;
while (temp != null) {
if (temp.tag == p.block_id) {
temp.size += p.size;
break;
}
temp = temp.next;
}
}
// Driver Code
public static void main(String[] args)
{
int blockSize[] = { 100, 500, 200 };
int processSize[] = { 417, 112, 426, 95 };
int m = blockSize.length;
int n = processSize.length;
for (int i = 0; i < m; i++)
create_free(blockSize[i]);
for (int i = 0; i < n; i++)
create_alloc(processSize[i]);
print_alloc();
// Block of tag id 0 deleted
// to free space for block of size 426
delete_alloc(0);
create_alloc(426);
System.out.println("After deleting block"
+ " with tag id 0.");
print_alloc();
}
}
// This code is contributed by Lovely Jain
Python3
# Python3 implementation of the First
# sit memory management algorithm
# using linked list
# Two global counters
g = 0; k = 0
# Structure for free list
class free:
def __init__(self):
self.tag=-1
self.size=0
self.next=None
free_head = None; prev_free = None
# Structure for allocated list
class alloc:
def __init__(self):
self.block_id=-1
self.tag=-1
self.size=0
self.next=None
alloc_head = None;prev_alloc = None
# Function to create free
# list with given sizes
def create_free(c):
global g,prev_free,free_head
p = free()
p.size = c
p.tag = g
p.next = None
if free_head is None:
free_head = p
else:
prev_free.next = p
prev_free = p
g+=1
# Function to print free list which
# prints free blocks of given sizes
def print_free():
p = free_head
print("Tag\tSize")
while (p != None) :
print("{}\t{}".format(p.tag,p.size))
p = p.next
# Function to print allocated list which
# prints allocated blocks and their block ids
def print_alloc():
p = alloc_head
print("Tag\tBlock ID\tSize")
while (p is not None) :
print("{}\t{}\t{}\t".format(p.tag,p.block_id,p.size))
p = p.next
# Function to allocate memory to
# blocks as per First fit algorithm
def create_alloc(c):
global k,alloc_head
# create node for process of given size
q = alloc()
q.size = c
q.tag = k
q.next = None
p = free_head
# Iterate to find first memory
# block with appropriate size
while (p != None) :
if (q.size <= p.size):
break
p = p.next
# Node found to allocate
if (p != None) :
# Adding node to allocated list
q.block_id = p.tag
p.size -= q.size
if (alloc_head == None):
alloc_head = q
else :
prev_alloc = alloc_head
while (prev_alloc.next != None):
prev_alloc = prev_alloc.next
prev_alloc.next = q
k+=1
else: # Node found to allocate space from
print("Block of size {} can't be allocated".format(c))
# Function to delete node from
# allocated list to free some space
def delete_alloc(t):
global alloc_head
# Standard delete function
# of a linked list node
p = alloc_head; q = None
# First, find the node according
# to given tag id
while (p != None) :
if (p.tag == t):
break
q = p
p = p.next
if (p == None):
print("Tag ID doesn't exist")
elif (p == alloc_head):
alloc_head = alloc_head.next
else:
q.next = p.next
temp = free_head
while (temp != None) :
if (temp.tag == p.block_id) :
temp.size += p.size
break
temp = temp.next
# Driver Code
if __name__ == '__main__':
blockSize = [100, 500, 200]
processSize = [417, 112, 426, 95]
m = len(blockSize)
n = len(processSize)
for i in range(m):
create_free(blockSize[i])
for i in range(n):
create_alloc(processSize[i])
print_alloc()
# Block of tag id 0 deleted
# to free space for block of size 426
delete_alloc(0)
create_alloc(426)
print("After deleting block with tag id 0.")
print_alloc()
C#
// C# implementation of the First
// sit memory management algorithm
// using linked list
using System;
public class MainClass {
// Two global counters
public static int g = 0, k = 0;
public class Free {
// Structure for free list
public int tag;
public int size;
public Free next;
}
public static Free free_head = null, prev_free = null;
// Structure for allocated list
public class Alloc {
public int block_id;
public int tag;
public int size;
public Alloc next;
}
public static Alloc alloc_head = null, prev_alloc
= null;
// Function to create free
// list with given sizes
public static void CreateFree(int c)
{
Free p = new Free();
p.size = c;
p.tag = g;
p.next = null;
if (free_head == null)
free_head = p;
else
prev_free.next = p;
prev_free = p;
g++;
}
// Function to print free list which
// prints free blocks of given sizes
public static void PrintFree()
{
Free p = free_head;
Console.WriteLine("Tag\tSize");
while (p != null) {
Console.WriteLine(p.tag + "\t" + p.size);
p = p.next;
}
}
// Function to print allocated list which
// prints allocated blocks and their block ids
public static void PrintAlloc()
{
// create node for process of given size
Alloc p = alloc_head;
Console.WriteLine("Tag\tBlock ID\tSize");
while (p != null) {
// Iterate to find first memory
// block with appropriate size
Console.WriteLine(p.tag + "\t " + p.block_id
+ "\t\t" + p.size);
p = p.next;
}
}
public static void CreateAlloc(int c)
{
Alloc q = new Alloc();
q.size = c;
q.tag = k;
q.next = null;
Free p = free_head;
while (p != null) {
if (q.size <= p.size)
break;
p = p.next;
}
if (p != null) {
// Adding node to allocated list
q.block_id = p.tag;
p.size -= q.size;
if (alloc_head == null)
alloc_head = q;
else {
prev_alloc = alloc_head;
while (prev_alloc.next != null)
prev_alloc = prev_alloc.next;
prev_alloc.next = q;
}
k++;
}
else // Node found to allocate space from
Console.WriteLine("Block of size " + c
+ " can't be allocated");
}
// Function to delete node from
// allocated list to free some space
public static void DeleteAlloc(int t)
{
// Standard delete function
// of a linked list node
Alloc p = alloc_head, q = null;
while (p != null) {
// First, find the node according
// to given tag id
if (p.tag == t)
break;
q = p;
p = p.next;
}
if (p == null)
Console.WriteLine("Tag ID doesn't exist");
else if (p == alloc_head)
alloc_head = alloc_head.next;
else
q.next = p.next;
Free temp = free_head;
while (temp != null) {
if (temp.tag == p.block_id) {
temp.size += p.size;
break;
}
temp = temp.next;
}
}
// Driver Code
public static void Main()
{
int[] blockSize = { 100, 500, 200 };
int[] processSize = { 417, 112, 426, 95 };
int m = blockSize.Length;
int n = processSize.Length;
for (int i = 0; i < m; i++)
CreateFree(blockSize[i]);
for (int i = 0; i < n; i++)
CreateAlloc(processSize[i]);
PrintAlloc();
// Block of tag id 0 deleted
// to free space for block of size 426
DeleteAlloc(0);
CreateAlloc(426);
Console.WriteLine(
"After deleting block with tag id 0.");
PrintAlloc();
}
}
JavaScript
//Javascript Equivalent
// Two global counters
let g = 0; let k = 0
// Structure for free list
class Free {
constructor() {
this.tag = -1;
this.size = 0;
this.next = null;
}
}
let freeHead = null; let prevFree = null;
// Structure for allocated list
class Alloc {
constructor() {
this.blockId = -1;
this.tag = -1;
this.size = 0;
this.next = null;
}
}
let allocHead = null; let prevAlloc = null;
// Function to create free
// list with given sizes
function createFree(c) {
let p = new Free();
p.size = c;
p.tag = g;
p.next = null;
if (freeHead === null) {
freeHead = p;
} else {
prevFree.next = p;
}
prevFree = p;
g+=1;
}
// Function to print free list which
// prints free blocks of given sizes
function printFree() {
let p = freeHead;
console.log("Tag\tSize");
while (p !== null) {
console.log(`${p.tag}\t${p.size}`);
p = p.next;
}
}
// Function to print allocated list which
// prints allocated blocks and their block ids
function printAlloc() {
let p = allocHead;
console.log("Tag\tBlock ID\tSize");
while (p !== null) {
console.log(`${p.tag}\t${p.blockId}\t${p.size}\t`);
p = p.next;
}
}
// Function to allocate memory to
// blocks as per First fit algorithm
function createAlloc(c) {
let q = new Alloc();
q.size = c;
q.tag = k;
q.next = null;
let p = freeHead;
// Iterate to find first memory
// block with appropriate size
while (p !== null) {
if (q.size <= p.size) {
break;
}
p = p.next;
}
// Node found to allocate
if (p !== null) {
// Adding node to allocated list
q.blockId = p.tag;
p.size -= q.size;
if (allocHead === null) {
allocHead = q;
} else {
prevAlloc = allocHead;
while (prevAlloc.next !== null) {
prevAlloc = prevAlloc.next;
}
prevAlloc.next = q;
}
k+=1;
} else { // Node found to allocate space from
console.log(`Block of size ${c} can't be allocated`);
}
}
// Function to delete node from
// allocated list to free some space
function deleteAlloc(t) {
// Standard delete function
// of a linked list node
let p = allocHead; let q = null;
// First, find the node according
// to given tag id
while (p !== null) {
if (p.tag === t) {
break;
}
q = p;
p = p.next;
}
if (p === null) {
console.log("Tag ID doesn't exist");
} else if (p === allocHead) {
allocHead = allocHead.next;
} else {
q.next = p.next;
}
let temp = freeHead;
while (temp !== null) {
if (temp.tag === p.blockId) {
temp.size += p.size;
break;
}
temp = temp.next;
}
}
// Driver Code
function main() {
let blockSize = [100, 500, 200];
let processSize = [417, 112, 426, 95];
let m = blockSize.length;
let n = processSize.length;
for (let i = 0; i < m; i++) {
createFree(blockSize[i]);
}
for (let i = 0; i < n; i++) {
createAlloc(processSize[i]);
}
printAlloc();
// Block of tag id 0 deleted
// to free space for block of size 426
deleteAlloc(0);
createAlloc(426);
console.log("After deleting block with tag id 0.");
printAlloc();
}
main();
Output: Block of size 426 can't be allocated
Tag Block ID Size
0 1 417
1 2 112
2 0 95
After deleting block with tag id 0.
Tag Block ID Size
1 2 112
2 0 95
3 1 426
Time complexity of the First Fit memory management algorithm is O(n), where n is the number of memory blocks. When a process is to be allocated, it will traverse the whole list of free blocks and check for the first block which is capable of accommodating the process. Hence, the time complexity is O(n).
Auxiliary Space complexity of the First Fit memory management algorithm is O(n), where n is the number of memory blocks. This is because the algorithm requires two linked lists for storing the free and allocated blocks. The free list stores the details of free blocks whereas the allocated list stores the details of allocated blocks. Hence, the space complexity is O(n).
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem