Run Length Decoding in Linked List

21 Jun, 2021
Given an encoded Linked List which is encoded using the Run Length Encoding algorithm. The task is to decode the given linked list and generate the input string.Run Length Encoding: In run length encoding, the input string is encoded by replacing a substring of repeated character in the string by the character followed by its count. If the character is single and is non-repeating than it’s count is not added. For Example, if the input string is “wwwwaaadexxxxxx”, then the function should return “w4a3dex6”Examples:  
Input : List = a->5->b->r->3->NULL Output : string = “aaaaabrrr” Explanation : From the linked list, the character is ‘a’ and it’s count is 5 so the character is repeated 5 times. The next character is ‘b’ and the next character to it is not a number hence the character ‘b’ is repeated only once. The next character is ‘r’ and the count is 3 hence the character is repeated 3 times.Input : List = a->b->r->3->a->3->NULL Output : string = “abrrraaa”  
 
Approach:  
Traverse through the linked list.
Store the current character in a variable c.
Check if the next node is a number and store the number in count else count is 1.
Append the character c to the list count times.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to decode a linked list#include <bits/stdc++.h>using namespace std; // Linked list nodestruct Node {    char data;    struct Node* next;}; // Utility function to create a new NodeNode* newNode(char data){    Node* temp = new Node;    temp->data = data;    temp->next = NULL;     return temp;} // Function to append nodes to a listvoid append(struct Node* head_ref, char new_data){    struct Node* new_node = new Node;     struct Node* last = head_ref;     new_node->data = new_data;     new_node->next = NULL;     if (head_ref == NULL) {        head_ref = new_node;        return;    }     while (last->next != NULL)        last = last->next;     last->next = new_node;    return;} // Function to print listvoid printList(Node* node){    while (node != NULL) {        cout << node->data << " ";         node = node->next;    }} // Function to decode the linked liststring decodeList(Node* head){    Node* p = head;    string res = "";    int count;     // While there are nodes left    while (p) {         // To store the count by which the current        // character needs to be repeated        count = 0;         // Get the current character        char c = p->data;        if (p->next) {            Node* temp = p->next;             // If current node is a digit            if (temp && temp->data >= '0'                && temp->data <= '9') {                 // Generate the integer from                // the consecutive digits                while (temp && temp->data >= '0'                       && temp->data <= '9') {                    count = count * 10 + (temp->data - '0');                    temp = temp->next;                }                p = temp;            }            else {                count = 1;                p = p->next;            }        }        else {            count = 1;            p = p->next;        }         // Repeat the character count times        for (int i = 0; i < count; i++) {            res += c;        }    }     return res;} // Driver codeint main(){    // Creating the linked list    Node* head = newNode('a');    head->next = newNode('5');    head->next->next = newNode('b');    head->next->next->next = newNode('r');     cout << decodeList(head);     return 0;}
// Java program to decode a linked listclass GFG {     // 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 = new Node();         Node last = head_ref;         new_node.data = new_data;         new_node.next = null;         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 decode the linked list    static String decodeList(Node head)    {        // Pointer used to traverse through all        // the nodes in the list        Node p = head;         // String to store the decoded message        String res = "";         int count;         // While there are nodes left        while (p != null) {             // To store the count by which the current            // character needs to be repeated            count = 0;             // Get the current character            char c = p.data;            if (p.next != null) {                Node temp = p.next;                 // If current node is a digit                if (temp != null && temp.data >= '0'                    && temp.data <= '9') {                     // Generate the integer from                    // the consecutive digits                    while (temp != null && temp.data >= '0'                           && temp.data <= '9') {                        count = count * 10 + (temp.data - '0');                        temp = temp.next;                    }                    p = temp;                }                else {                    count = 1;                    p = p.next;                }            }            else {                count = 1;                p = p.next;            }             // Repeat the character count times            for (int i = 0; i < count; i++) {                res += c;            }        }         return res;    }     // Driver code    public static void main(String args[])    {        // Creating the linked list        Node head = newNode('a');        head.next = newNode('5');        head.next.next = newNode('b');        head.next.next.next = newNode('r');         System.out.println(decodeList(head));    }} /* This code contributed by PrinciRaj1992 */
# Python3 program to decode a linked list  # Linked list nodeclass Node:      def __init__(self, data):               self.data = data        self.next = None  # Utility function to create a Nodedef newNode(data):    temp = Node(data);    temp.next = None;      return temp; # Function to append nodes to a listdef append(head_ref, new_data):    new_node = Node;    last = head_ref;    new_node.data = new_data;    new_node.next = None;    if (head_ref == None):        head_ref = new_node;        return;    while (last.next != None):        last = last.next;    last.next = new_node;    return;  # Function to print listdef printList(node):    while (node != None):               print(node.data, end = ' ')        node = node.next;      # Function to decode the linked listdef decodeList(head):    p = head;    res = "";    count = 0      # While there are nodes left    while (p != None):          # To store the count by which the current        # character needs to be repeated        count = 0;          # Get the current character        c = p.data;        if (p.next != None):                         temp = p.next;              # If current node is a digit            if (temp != None and ord(temp.data) >= ord('0')                and ord(temp.data) <= ord('9')):                  # Generate the integer from                # the consecutive digits                while (temp != None and ord(temp.data) >= ord('0')                       and ord(temp.data) <= ord('9')):                    count = count * 10 + ord(temp.data) - ord('0')                    temp = temp.next;                             p = temp;                         else:                count = 1;                p = p.next;                   else:            count = 1;            p = p.next;                  # Repeat the character count times        for i in range(0, count):                  res += c;    return res;  # Driver codeif __name__=='__main__':         # Creating the linked list    head = newNode('a');    head.next = newNode('5');    head.next.next = newNode('b');    head.next.next.next = newNode('r');      print(decodeList(head))   # This code is contributed by rutvik_56
// C# program to decode a linked listusing System; public class GFG {     // 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 = new Node();         Node last = head_ref;         new_node.data = new_data;         new_node.next = null;         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 decode the linked list    static String decodeList(Node head)    {        // Pointer used to traverse through all        // the nodes in the list        Node p = head;         // String to store the decoded message        String res = "";         int count;         // While there are nodes left        while (p != null) {             // To store the count by which the current            // character needs to be repeated            count = 0;             // Get the current character            char c = p.data;            if (p.next != null) {                Node temp = p.next;                 // If current node is a digit                if (temp != null && temp.data >= '0'                    && temp.data <= '9') {                     // Generate the integer from                    // the consecutive digits                    while (temp != null && temp.data >= '0'                           && temp.data <= '9') {                        count = count * 10 + (temp.data - '0');                        temp = temp.next;                    }                    p = temp;                }                else {                    count = 1;                    p = p.next;                }            }            else {                count = 1;                p = p.next;            }             // Repeat the character count times            for (int i = 0; i < count; i++) {                res += c;            }        }         return res;    }     // Driver code    public static void Main(String[] args)    {        // Creating the linked list        Node head = newNode('a');        head.next = newNode('5');        head.next.next = newNode('b');        head.next.next.next = newNode('r');         Console.WriteLine(decodeList(head));    }} // This code is contributed by 29AjayKumar
<script>       // JavaScript program to decode a linked list      // 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 = new Node();         var last = head_ref;         new_node.data = new_data;         new_node.next = null;         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 decode the linked list      function decodeList(head) {        // Pointer used to traverse through all        // the nodes in the list        var p = head;         // String to store the decoded message        var res = "";         var count;         // While there are nodes left        while (p != null) {          // To store the count by which the current          // character needs to be repeated          count = 0;           // Get the current character          var c = p.data;          if (p.next != null) {            var temp = p.next;             // If current node is a digit            if (temp != null && temp.data >= "0" &&                temp.data <= "9") {              // Generate the integer from              // the consecutive digits              while (temp != null && temp.data >= "0" &&                     temp.data <= "9") {                count = count * 10 + (temp.data - "0");                temp = temp.next;              }              p = temp;            } else {              count = 1;              p = p.next;            }          } else {            count = 1;            p = p.next;          }           // Repeat the character count times          for (var i = 0; i < count; i++) {            res += c;          }        }         return res;      }       // Driver code      // Creating the linked list      var head = newNode("a");      head.next = newNode("5");      head.next.next = newNode("b");      head.next.next.next = newNode("r");       document.write(decodeList(head));       </script>
aaaaabr
 
princiraj1992
29AjayKumar
ManishKumar85
gp6
rutvik_56
rdtank
encoding-decoding
String-Run Length Encoding
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.