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)
GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details
- 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
- Append odd position nodes in reverse at the end of even positioned nodes in a Linked List
- Splitting starting N nodes into new Circular Linked List while preserving the old nodes
- 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
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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