Program to implement Run Length Encoding using Linked Lists
Last Updated :
11 Jul, 2025
Given a Linked List as the input. The task is to encode the given linked list using Run Length Encoding. That is, to replace a block of contiguous characters by the character followed by it's count.
For Example, in Run Length Encoding "a->a->a->a->a" will be replaced by "a->5".
Note: For non-repeating nodes, do not append count 1. For example, a->b->b will be replaced by "a->b->2" and not "a->1->b->2".
Examples:
Input : List = a->a->a->a->a->b->r->r->r->NULL
Output : a->5->b->r->3->NULL
Explanation :
The character 'a' repeats 5 times.
The character 'b' repeats 1 time.
The character 'r' repeats 3 times.
Hence the output is a->5->b->r->3->NULL.
Input : a->a->a->a->a->a->a->a->a->a->b->r->r->r->a->a->a->NULL
Output : a->1->0->b->r->3->a->3->NULL
Approach:
- Traverse through the list.
- Consider the first character as c.
- Consider the current character as x.
- If the character is the same as c then increment the count.
- If the characters are not same then add the count to the list and append the next character to the list reset the count to 1.
Implementation:
C++
// C++ program to encode a linked list
// using Run Length Encoding
#include <bits/stdc++.h>
using namespace std;
// A linked list node
struct Node {
char data;
struct Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
// Function to append nodes to a list
void append(struct Node* head_ref, char new_data)
{
struct Node* new_node = new Node(new_data);
struct Node* last = head_ref;
if (head_ref == NULL) {
head_ref = new_node;
return;
}
while (last->next != NULL)
last = last->next;
last->next = new_node;
return;
}
// Function to print list
void printList(Node* node)
{
while (node != NULL) {
cout << node->data << " ";
node = node->next;
}
}
// Function to encode the list
void RLE(Node* head)
{
// Pointer used to traverse through
// all the nodes in the list
Node* p = head;
// List to store the encoded message
Node* temp = new Node(p->data);
// Store the first character in c
char c = p->data;
p = p->next;
// Count to count the number of
// continuous elements
int count = 1;
// Traverse through all the
// elements in the list
while (p != NULL) {
// Store the current character in x
char x = p->data;
// If the characters are same
if (c == x)
// Increment count
count++;
// Else
else {
// If the count is greater than 1
if (count > 1) {
// Append the count to list
if (count > 9)
append(temp, '0' + (count / 10));
append(temp, '0' + (count % 10));
}
// Reset the count
count = 1;
// Add the next character
// to the list
append(temp, x);
// Take the character to check as
// the current character
c = x;
}
p = p->next;
}
// Add the final count
if (count != 0)
append(temp, '0' + count);
// Print the list
printList(temp);
}
// Driver code
int main()
{
// Creating the linked list
Node* head = new Node('a');
head->next = new Node('a');
head->next->next = new Node('a');
head->next->next->next = new Node('b');
head->next->next->next->next = new Node('r');
head->next->next->next->next->next = new Node('r');
RLE(head);
return 0;
}
Java
// Java program to encode a linked list
// using Run Length Encoding
class GFG
{
// A linked list node
static class Node
{
char data;
Node next;
};
// Utility function to create a new Node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.next = null;
return temp;
}
// Function to append nodes to a list
static void append(Node head_ref, char new_data)
{
Node new_node = newNode(new_data);
Node last = head_ref;
if (head_ref == null)
{
head_ref = new_node;
return;
}
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
// Function to print list
static void printList(Node node)
{
while (node != null)
{
System.out.print(node.data+" ");
node = node.next;
}
}
// Function to encode the list
static void RLE(Node head)
{
// Pointer used to traverse through
// all the nodes in the list
Node p = head;
// List to store the encoded message
Node temp = newNode(p.data);
// Store the first character in c
char c = p.data;
p = p.next;
// Count to count the number of
// continuous elements
int count = 1;
// Traverse through all the
// elements in the list
while (p != null)
{
// Store the current character in x
char x = p.data;
// If the characters are same
if (c == x)
// Increment count
count++;
// Else
else
{
// If the count is greater than 1
if (count > 1)
{
// Append the count to list
if (count > 9)
append(temp, (char) ('0' + (count / 10)));
append(temp, (char) ('0' + (count % 10)));
}
// Reset the count
count = 1;
// Add the next character
// to the list
append(temp, x);
// Take the character to check as
// the current character
c = x;
}
p = p.next;
}
// Add the final count
if (count != 0)
append(temp, (char) ('0' + count));
// Print the list
printList(temp);
}
// Driver code
public static void main(String[] args)
{
// Creating the linked list
Node head = newNode('a');
head.next = newNode('a');
head.next.next = newNode('a');
head.next.next.next = newNode('b');
head.next.next.next.next = newNode('r');
head.next.next.next.next.next = newNode('r');
RLE(head);
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python3 program to encode a linked list
# using Run Length Encoding
# A linked list node
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to append nodes to a list
def append(head_ref, new_data):
_node = Node(new_data);
last = head_ref;
if (head_ref == None):
head_ref =_node;
return;
while (last.next != None):
last = last.next;
last.next =_node;
return;
# Function to print list
def printList(node):
while (node != None):
print(node.data, end = ' ')
node = node.next;
# Function to encode the list
def RLE(head):
# Pointer used to traverse through
# all the nodes in the list
p = head;
# List to store the encoded message
temp = Node(p.data);
# Store the first character in c
c = p.data;
p = p.next;
# Count to count the number of
# continuous elements
count = 1;
# Traverse through all the
# elements in the list
while (p != None):
# Store the current character in x
x = p.data;
# If the characters are same
if (c == x):
# Increment count
count += 1
# Else
else:
# If the count is greater than 1
if (count > 1):
# Append the count to list
if (count > 9):
append(temp, chr(ord('0') + (count // 10)));
append(temp, chr(ord('0') + (count % 10)));
# Reset the count
count = 1;
# Add the next character
# to the list
append(temp, x);
# Take the character to check as
# the current character
c = x;
p = p.next;
# Add the final count
if (count != 0):
append(temp, chr(ord('0') + count))
# Print the list
printList(temp);
# Driver code
if __name__=='__main__':
# Creating the linked list
head = Node('a');
head.next = Node('a');
head.next.next = Node('a');
head.next.next.next = Node('b');
head.next.next.next.next = Node('r');
head.next.next.next.next.next = Node('r');
RLE(head);
# This code is contributed by pratham76
C#
// C# program to encode a linked list
// using Run Length Encoding
using System;
class GFG
{
// A linked list node
public class Node
{
public char data;
public Node next;
};
// Utility function to create a new Node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.next = null;
return temp;
}
// Function to append nodes to a list
static void append(Node head_ref, char new_data)
{
Node new_node = newNode(new_data);
Node last = head_ref;
if (head_ref == null)
{
head_ref = new_node;
return;
}
while (last.next != null)
last = last.next;
last.next = new_node;
return;
}
// Function to print list
static void printList(Node node)
{
while (node != null)
{
Console.Write(node.data+" ");
node = node.next;
}
}
// Function to encode the list
static void RLE(Node head)
{
// Pointer used to traverse through
// all the nodes in the list
Node p = head;
// List to store the encoded message
Node temp = newNode(p.data);
// Store the first character in c
char c = p.data;
p = p.next;
// Count to count the number of
// continuous elements
int count = 1;
// Traverse through all the
// elements in the list
while (p != null)
{
// Store the current character in x
char x = p.data;
// If the characters are same
if (c == x)
// Increment count
count++;
// Else
else
{
// If the count is greater than 1
if (count > 1)
{
// Append the count to list
if (count > 9)
append(temp, (char) ('0' + (count / 10)));
append(temp, (char) ('0' + (count % 10)));
}
// Reset the count
count = 1;
// Add the next character
// to the list
append(temp, x);
// Take the character to check as
// the current character
c = x;
}
p = p.next;
}
// Add the final count
if (count != 0)
append(temp, (char) ('0' + count));
// Print the list
printList(temp);
}
// Driver code
public static void Main()
{
// Creating the linked list
Node head = newNode('a');
head.next = newNode('a');
head.next.next = newNode('a');
head.next.next.next = newNode('b');
head.next.next.next.next = newNode('r');
head.next.next.next.next.next = newNode('r');
RLE(head);
}
}
/* This code contributed by PrinciRaj1992 */
JavaScript
<script>
// JavaScript program to encode a linked list
// using Run Length Encoding
// A linked list node
class Node {
constructor() {
this.data = 0;
this.next = null;
}
}
// Utility function to create a new Node
function newNode(data) {
var temp = new Node();
temp.data = data;
temp.next = null;
return temp;
}
// Function to append nodes to a list
function append(head_ref, new_data) {
var new_node = newNode(new_data);
var last = head_ref;
if (head_ref == null) {
head_ref = new_node;
return;
}
while (last.next != null) last = last.next;
last.next = new_node;
return;
}
// Function to print list
function printList(node) {
while (node != null) {
document.write(node.data + " ");
node = node.next;
}
}
// Function to encode the list
function RLE(head) {
// Pointer used to traverse through
// all the nodes in the list
var p = head;
// List to store the encoded message
var temp = newNode(p.data);
// Store the first character in c
var c = p.data;
p = p.next;
// Count to count the number of
// continuous elements
var count = 1;
// Traverse through all the
// elements in the list
while (p != null) {
// Store the current character in x
var x = p.data;
// If the characters are same
if (c == x)
// Increment count
count++;
// Else
else {
// If the count is greater than 1
if (count > 1) {
// Append the count to list
if (count > 9)
append(
temp,
String.fromCharCode("0".charCodeAt(0) +
parseInt(count / 10))
);
append(
temp,
String.fromCharCode("0".charCodeAt(0) +
(count % 10))
);
}
// Reset the count
count = 1;
// Add the next character
// to the list
append(temp, x);
// Take the character to check as
// the current character
c = x;
}
p = p.next;
}
// Add the final count
if (count != 0)
append(temp, String.fromCharCode("0".charCodeAt(0) +
count));
// Print the list
printList(temp);
}
// Driver code
// Creating the linked list
var head = newNode("a");
head.next = newNode("a");
head.next.next = newNode("a");
head.next.next.next = newNode("b");
head.next.next.next.next = newNode("r");
head.next.next.next.next.next = newNode("r");
RLE(head);
</script>
Complexity Analysis:
- Time Complexity: O(N2)
- Auxiliary Space: O(1)
In Place Conversion:
The idea here is to modify the existing list based on the frequency of characters rather than creating a new list if system enforces space constraint.
- Traverse through the list.
- Compare current character with the next character. If same then increment the count value.
- Delete nodes whose frequency is greater than 2.
- If characters are not same, then update the count value.
C++
// C++ program implementing run length encoding
#include<stdio.h>
#include<stdlib.h>
struct Node
{
char data;
struct Node* next;
Node(int x)
{
data = x;
next = NULL;
}
};
// Function to add node to the list
Node* insert (Node *head, int data)
{
if (head == NULL)
return new Node(data);
head->next = insert(head->next, data);
return head;
}
// Function to print the list
void printList (Node* head)
{
while (head != NULL)
{
printf ("%c ",head->data);
head = head->next;
}
return;
}
void runLengthEncode (Node* head)
{
Node* temp = NULL;
Node* ptr = NULL;
int count = 0; //count the number of characters
temp = head;
while (temp != NULL)
{
ptr = temp;
count = 1;
//check if current data and next data is same.If same, then increment count
while (temp->next != NULL &&
temp->data == temp->next->data)
{
count++;
if (count > 2)
{
// delete only when the node value is repeated more than
// twice.
ptr->next = temp->next;
free(temp);
temp = ptr;
}
temp = temp->next;
}
// update only when the node value is repeated more than one time.
if (count > 1)
temp->data = count + '0';
temp = temp->next;
}
return;
}
// Driver code
int main()
{
// Creating the linked list
Node* head = new Node('a');
head->next = new Node('a');
head->next->next = new Node('a');
head->next->next->next = new Node('b');
head->next->next->next->next = new Node('r');
head->next->next->next->next->next = new Node('r');
runLengthEncode (head);
printList (head);
return 0;
}
Java
// java program implementing run length encoding
class GFG {
// A linked list node
static class Node
{
char data;
Node next;
};
// Utility function to create a new Node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.next = null;
return temp;
}
// Function to add node to the list
static Node insert(Node head, char data)
{
if (head == null)
return newNode(data);
head.next = insert(head.next, data);
return head;
}
// Function to print the list
static void printList (Node head)
{
while (head != null)
{
System.out.print(head.data + " ");
head = head.next;
}
return;
}
static void runLengthEncode (Node head)
{
Node temp;
Node ptr;
int count = 0; //count the number of characters
temp = head;
while (temp != null)
{
ptr = temp;
count = 1;
//check if current data and next data is same.If same, then increment count
while (temp.next != null &&
temp.data == temp.next.data)
{
count++;
if (count > 2)
{
// delete only when the node value is repeated more than
// twice.
ptr.next = temp.next;
temp= null;
temp = ptr;
}
temp = temp.next;
}
// update only when the node value is repeated more than one time.
if (count > 1)
temp.data = (char) (count + '0');
temp = temp.next;
}
return;
}
// Driver code
public static void main(String [] args)
{
// Creating the linked list
Node head = newNode('a');
head.next = newNode('a');
head.next.next = newNode('a');
head.next.next.next = newNode('b');
head.next.next.next.next = newNode('r');
head.next.next.next.next.next = newNode('r');
runLengthEncode (head);
printList (head);
}
}
// This code is contributed by AR_Gaurav
Python3
# Python3 program implementing run length encoding
class Node:
def __init__(self, data):
self.data = data
self.next = None
# Function to add node to the list
def insert(head, data):
if (head == None):
return Node(data);
head.next = insert(head.next, data);
return head;
# Function to print the list
def printList(head):
while (head != None):
print(head.data, end = ' ')
head = head.next;
return;
def runLengthEncode(head):
temp = None;
ptr = None;
count = 0; #count the number of characters
temp = head;
while (temp != None):
ptr = temp;
count = 1;
# check if current data and next data
# is same.If same, then increment count
while (temp.next != None and
temp.data == temp.next.data):
count += 1
if (count > 2):
# delete only when the node
# value is repeated more than
# twice.
ptr.next = temp.next;
del (temp);
temp = ptr;
temp = temp.next;
# update only when the node value
# is repeated more than one time.
if (count > 1):
temp.data = count ;
temp = temp.next;
return;
# Driver code
if __name__=='__main__':
# Creating the linked list
head = Node('a');
head.next = Node('a');
head.next.next = Node('a');
head.next.next.next = Node('b');
head.next.next.next.next = Node('r');
head.next.next.next.next.next = Node('r');
runLengthEncode(head);
printList(head);
# This code is contributed by rutvik_56
C#
using System;
class GFG
{
// A linked list node
class Node
{
public char data;
public Node next;
};
// Utility function to create a new Node
static Node newNode(char data)
{
Node temp = new Node();
temp.data = data;
temp.next = null;
return temp;
}
// Function to add node to the list
static Node insert(Node head, char data)
{
if (head == null)
return newNode(data);
head.next = insert(head.next, data);
return head;
}
// Function to print the list
static void printList(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
static void runLengthEncode(Node head)
{
Node temp;
Node ptr;
int count = 0; // count the number of characters
temp = head;
while (temp != null)
{
ptr = temp;
count = 1;
// check if current data and next data is same. If same, then increment count
while (temp.next != null &&
temp.data == temp.next.data)
{
count++;
if (count > 2)
{
// delete only when the node value is repeated more than twice
ptr.next = temp.next;
temp = null;
temp = ptr;
}
temp = temp.next;
}
// update only when the node value is repeated more than one time
if (count > 1)
temp.data = (char)(count + '0');
temp = temp.next;
}
}
// Driver code
static void Main(string[] args)
{
// Creating the linked list
Node head = newNode('a');
head.next = newNode('a');
head.next.next = newNode('a');
head.next.next.next = newNode('b');
head.next.next.next.next = newNode('r');
head.next.next.next.next.next = newNode('r');
runLengthEncode(head);
printList(head);
}
}
JavaScript
<script>
// JavaScript program implementing
// run length encoding
class Node
{
constructor(x)
{
this.data=x;
this.next=null;
}
}
// Function to add node to the list
function insert (head,data)
{
if (head == null)
return new Node(data);
head.next = insert(head.next, data);
return head;
}
// Function to print the list
function printList (head)
{
while (head != null)
{
document.write(head.data+" ");
head = head.next;
}
return;
}
function runLengthEncode (head)
{
let temp = null;
let ptr = null;
let count = 0; //count the number of characters
temp = head;
while (temp != null)
{
ptr = temp;
count = 1;
//check if current data and next data is same.If same,
// then increment count
while (temp.next != null &&
temp.data == temp.next.data)
{
count++;
if (count > 2)
{
// delete only when the node value
// is repeated more than
// twice.
ptr.next = temp.next;
delete(temp);
temp = ptr;
}
temp = temp.next;
}
// update only when the node value is
// repeated more than one time.
if (count > 1)
temp.data = count ;
temp = temp.next;
}
return;
}
// Driver code
let head = new Node('a');
head.next = new Node('a');
head.next.next = new Node('a');
head.next.next.next = new Node('b');
head.next.next.next.next = new Node('r');
head.next.next.next.next.next = new Node('r');
runLengthEncode (head);
printList (head);
// This code is contributed by unknown2108
</script>
Complexity Analysis:
- Time Complexity: O(N)
- Auxiliary Space: O(1)
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