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).
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:
Time Complexity: O(N)
Auxiliary Space: O(1)
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Maximum sum of K consecutive nodes in the given Linked List
- Maximum length cycle that can be formed by joining two nodes of a binary tree
- Check if absolute difference of consecutive nodes is 1 in Linked List
- Find sum of even and odd nodes in a linked list
- Find the sum of last n nodes of the given Linked List
- Find the product of last N nodes of the given Linked List
- Find the product of first k nodes of the given Linked List
- Program to find average of all nodes in a Linked List
- Find the common nodes in two singly linked list
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Find first non-repeating character in a given string using Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Delete N nodes after M nodes of a linked list
- Linked List Sum of Nodes Between 0s
- Sum of all distinct nodes in a linked list
- Sum of the nodes of a Circular Linked List
- Sum of the nodes of a Singly Linked List
- Sum and Product of all the nodes which are less than K in the linked list
- Linked List Product of Nodes Between 0s
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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