Find the string formed by joining k consecutive nodes of linked list

Given an integer K and a linked list in which each node stores a single character. The task is to join every K consecutive nodes of the linked list to form a single word. Finally, print the string obtained by joining these words (space separated).

Examples:

Input: List = ‘a’ -> ‘b’ -> ‘c’ ->’d’ -> ‘e’ -> NULL, k = 3
Output: abc de
The first three nodes form the first word “abc”
and next two nodes form the second word “de”.

Input: List = ‘a’ -> ‘b’ -> ‘c’ -> ‘d’ -> ‘e’ -> ‘f’ -> NULL, k = 2
Output: ab cd ef

Approach: The idea is to traverse the linked list and keep adding character present at each node to the word formed so far. Keep track of the number of nodes traversed and when the count becomes equal to k, add the word formed so far to the resultant string, reset word to an empty string and reset the count to zero. Repeat this until the entire linked list is not traversed.



Below is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
  
// Structure of a node
struct Node {
    char data;
    Node* next;
};
  
// Function to get a new node
Node* getNode(char data)
{
    // Allocate space
    Node* newNode = new Node;
  
    // Put in data
    newNode->data = data;
    newNode->next = NULL;
    return newNode;
}
  
// Function to find string formed by joining words
// obtained by joining k consecutive nodes of
// linked list.
string findKWordString(Node* head, int k)
{
    // Stores the final string
    string ans = "";
  
    // Keep track of the number of
    // nodes traversed
    int cnt = 0;
  
    // Stores the word formed by k consecutive
    // nodes of the linked list
    string word = "";
  
    while (head) {
  
        // Check if k nodes are traversed
        // If yes then add the word obtained
        // to the result string
        if (cnt == k) {
            if (ans != "") {
                ans = ans + " ";
            }
  
            ans = ans + word;
            word = "";
            cnt = 0;
        }
  
        // Add the current character to the word
        // formed so far and increase the count
        word = word + string(1, head->data);
        cnt++;
        head = head->next;
    }
  
    // Add the final word to the result
    // Length of the final word can be less than k
    if (ans != " ") {
        ans = ans + " ";
    }
    ans = ans + word;
  
    return ans;
}
  
// Driver code
int main()
{
  
    // Create list: a -> b -> c -> d -> e
    Node* head = getNode('a');
    head->next = getNode('b');
    head->next->next = getNode('c');
    head->next->next->next = getNode('d');
    head->next->next->next->next = getNode('e');
  
    int k = 3;
  
    cout << findKWordString(head, k);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java implementation of the approach
class GFG{
  
// Class of a node
static class Node
{
    char data;
    Node next;
};
  
// Function to get a new node
static Node getNode(char data)
{
      
    // Allocate space
    Node newNode = new Node();
  
    // Put in data
    newNode.data = data;
    newNode.next = null;
    return newNode;
}
  
// Function to find string formed by 
// joining words obtained by joining 
// k consecutive nodes of linked list.
static String findKWordString(Node head, int k)
{
      
    // Stores the final string
    String ans = "";
  
    // Keep track of the number of
    // nodes traversed
    int cnt = 0;
  
    // Stores the word formed by k consecutive
    // nodes of the linked list
    String word = "";
  
    while (head != null)
    {
  
        // Check if k nodes are traversed
        // if yes then add the word obtained
        // to the result String
        if (cnt == k)
        {
            if (ans != ""
            {
                ans = (ans + " ");
            }
  
            ans = ans + word;
            word = "";
            cnt = 0;
        }
  
        // Add the current character to the word
        // formed so far and increase the count
        word = word + head.data;
        cnt++;
        head = head.next;
    }
  
    // Add the final word to the result
    // Length of the final word can be
    // less than k
    if (ans != " ")
    {
        ans = (ans + " ");
    }
    ans = ans + word;
    return ans;
}
  
// Driver code
public static void main(String[] args)
{
  
    // Create list: a.b.c.d.e
    Node head = getNode('a');
    head.next = getNode('b');
    head.next.next = getNode('c');
    head.next.next.next = getNode('d');
    head.next.next.next.next = getNode('e');
  
    int k = 3;
  
    System.out.print(findKWordString(head, k));
}
}
  
// This code is contributed by GauravRajput1

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# implementation of the approach
using System;
  
class GFG{
  
// Class of a node
class Node
{
    public char data;
    public Node next;
};
  
// Function to get a new node
static Node getNode(char data)
{
      
    // Allocate space
    Node newNode = new Node();
  
    // Put in data
    newNode.data = data;
    newNode.next = null;
    return newNode;
}
  
// Function to find string formed by 
// joining words obtained by joining 
// k consecutive nodes of linked list.
static String findKWordString(Node head, int k)
{
      
    // Stores the final string
    String ans = "";
  
    // Keep track of the number 
    // of nodes traversed
    int cnt = 0;
  
    // Stores the word formed by k 
    // consecutive nodes of the 
    // linked list
    String word = "";
  
    while (head != null)
    {
  
        // Check if k nodes are traversed
        // if yes then add the word obtained
        // to the result String
        if (cnt == k)
        {
            if (ans != ""
            {
                ans = (ans + " ");
            }
  
            ans = ans + word;
            word = "";
            cnt = 0;
        }
  
        // Add the current character to the word
        // formed so far and increase the count
        word = word + head.data;
        cnt++;
        head = head.next;
    }
  
    // Add the readonly word to the result
    // Length of the readonly word can be
    // less than k
    if (ans != " ")
    {
        ans = (ans + " ");
    }
    ans = ans + word;
    return ans;
}
  
// Driver code
public static void Main(String[] args)
{
  
    // Create list: a.b.c.d.e
    Node head = getNode('a');
    head.next = getNode('b');
    head.next.next = getNode('c');
    head.next.next.next = getNode('d');
    head.next.next.next.next = getNode('e');
  
    int k = 3;
  
    Console.Write(findKWordString(head, k));
}
}
  
// This code is contributed by gauravrajput1

chevron_right


Output:

abc de

Time Complexity: O(N)
Auxiliary Space: O(1)

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

A Programmer and A Machine learning Enthusiast

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : GauravRajput1