Given head of a linked list of integers and an integer k, your task is to modify the linked list as follows:
- Consider nodes in groups of size k. In every group, replace value of first node with group sum.
- Also, delete the elements of group except the first node.
- During traversal, if the remaining nodes in linked list are less than k then also do the above considering remaining nodes.
Examples:Â
Input: N = 6, K = 2Â
1->2->3->4->5->6Â
Output: 3 7 11
We have denoted grouping of k elements by (). The elements inside () are summed.Â
1 -> 2 -> 3 -> 4 -> 5 -> 6 -> nullÂ
(1 -> 2) -> 3 -> 4 -> 5 -> 6 -> nullÂ
(3) -> 3 -> 4 -> 5 -> 6 -> nullÂ
3 -> (3 -> 4) -> 5 -> 6 -> nullÂ
3 -> (7) -> 5 -> 6 -> nullÂ
3 -> 7 -> (5 -> 6) -> nullÂ
3 -> 7 -> (11) -> nullÂ
3 -> 7 -> 11 -> nullÂ
Approach:Â
Insert the given nodes in the Linked list. The approach of insertion has been discussed in this post. Once the nodes are inserted, iterate from the beginning of the list. Mark the first node as temp node. Iterate for the next k-1 nodes and sum up the nodes in sum variable. If the number of nodes is less than K, then replace the temp node’s data with sum and point temp to NULL.Â
If there is a group with K nodes, replace the temp’s data with sum and move temp to the node which is just after K nodes. Continue the above operation till temp points to NULL. Once temp reaches the end, it means all groups of size K has been traversed and the node has been replaced with the sum of nodes of size K. Once the operation of replacements have been done, the linked list thus formed can be printed. The method of printing the linked list has been discussed in this post.Â
Below is the implementation of the above approach:Â Â
C++
// C++ program for // SP - K Sum Â
#include <iostream> using namespace std; Â
// structure for linked list struct Node { Â Â Â Â long long data; Â Â Â Â Node* next; }; Â
// allocated new node Node* newNode( int key) { Â Â Â Â Node* temp = new Node; Â Â Â Â temp->data = key; Â Â Â Â temp->next = NULL; Â Â Â Â return temp; } Â
// function to insert node in a Linked List Node* insertNode(Node* head, int key) {     if (head == NULL)         head = newNode(key);     else         head->next = insertNode(head->next, key); Â
    return head; } Â
// traverse the node // to print it void print(Node* head) {     // traverse the linked list     while (head) {         cout << head->data << " " ;         head = head->next;     }     cout << endl; } Â
// function to perform the following operation void KSum(Node* head, int k) {     // initially pointing to start     Node* temp = head; Â
    // iterate till end     while (temp) { Â
        // dummy variable to store k         long long count = k; Â
        // summation of nodes         long long sum = 0; Â
        // currently at node from         // which iteration is done         Node* curr = temp; Â
        // till k nodes are visited and         // last node is not visited         while (count-- && curr) {             // add to sum the node data             sum = sum + curr->data; Â
            // move to the next node             curr = curr->next;         } Â
        // change pointer's data of temp to sum         temp->data = sum; Â
        // move temp to next pointer         temp->next = curr; Â
        // move temp to the next pointer         temp = temp->next;     } } Â
// Driver Code int main() { Â
    Node* head = NULL; Â
    // inserts nodes in the linked list     head = insertNode(head, 1);     head = insertNode(head, 2);     head = insertNode(head, 3);     head = insertNode(head, 4);     head = insertNode(head, 5);     head = insertNode(head, 6); Â
    int k = 2;     // Function call to perform the     // given operations     KSum(head, k); Â
    // print the linked list     print(head); Â
    return 0; } |
Java
// Java program for // SP - K Sum Â
import java.io.*; import java.util.*; Â
// structure for linked list class Node { Â Â Â Â int data; Â Â Â Â Node next; Â Â Â Â Node( int key) Â Â Â Â { Â Â Â Â Â Â Â Â data = key; Â Â Â Â Â Â Â Â next = null ; Â Â Â Â } } Â
class GFG { Â Â Â Â Â // allocated new node static Node head; Â
// function to insert node // in a Linked List public static Node insertNode(Node head, int key) {     if (head == null )         head = new Node(key);     else         head.next = insertNode(head.next, key); Â
    return head; } Â
// traverse the node // to print it public static void print(Node head) {     // traverse the linked list     while (head != null )     {         System.out.print(head.data + " " );         head = head.next;     }     System.out.println(); } Â
// function to perform // the following operation public static void KSum(Node head, int k) {     // initially pointing     // to start     Node temp = head; Â
    // iterate till end     while (temp != null )     { Â
        // dummy variable         // to store k         int count = k; Â
        // summation of nodes         int sum = 0 ; Â
        // currently at node from         // which iteration is done         Node curr = temp; Â
        // till k nodes are visited and         // last node is not visited         while (count > 0 && curr != null )         {             // add to sum the node data             sum = sum + curr.data; Â
            // move to the next node             curr = curr.next;             count--;         } Â
        // change pointer's data         // of temp to sum         temp.data = sum; Â
        // move temp to         // next pointer         temp.next = curr; Â
        // move temp to         // the next pointer         temp = temp.next;     }          //return temp; } Â
// Driver Code public static void main(String args[]) { Â Â Â Â Â head = null ; Â
    // inserts nodes in     // the linked list     head = insertNode(head, 1 );     head = insertNode(head, 2 );     head = insertNode(head, 3 );     head = insertNode(head, 4 );     head = insertNode(head, 5 );     head = insertNode(head, 6 ); Â
    int k = 2 ;          // Function call to perform     // the given operations      KSum(head, k); Â
    // print the linked list     print(head); } } |
Python3
# Python program for # SP - K Sum Â
# structure for linked list class Node:     def __init__( self , key):         self .data = key         self . next = None Â
# function to insert node in a Linked List def insertNode(head: Node, key: int ) - > Node: Â Â Â Â if head is None : Â Â Â Â Â Â Â Â head = Node(key) Â Â Â Â else : Â Â Â Â Â Â Â Â head. next = insertNode(head. next , key) Â
    return head Â
# traverse the node # to print it def Print (head: Node): Â
    # traverse the linked list     while head:         print (head.data, end = " " )         head = head. next     print () Â
# function to perform the following operation def KSum(head: Node, k: int ): Â
    # initially pointing to start     temp = head Â
    # iterate till end     while temp: Â
        # dummy variable to store k         count = k Â
        # summation of nodes         sum = 0 Â
        # currently at node from         # which iteration is done         curr = temp Â
        # till k nodes are visited and         # last node is not visited         while count and curr: Â
            # add to sum the node data             sum = sum + curr.data Â
            # move to the next node             curr = curr. next             count - = 1 Â
        # change pointer's data of temp to sum         temp.data = sum Â
        # move temp to next pointer         temp. next = curr Â
        # move temp to the next pointer         temp = temp. next Â
# Driver Code if __name__ = = "__main__" : Â Â Â Â head = None Â
    # inserts nodes in the linked list     head = insertNode(head, 1 )     head = insertNode(head, 2 )     head = insertNode(head, 3 )     head = insertNode(head, 4 )     head = insertNode(head, 5 )     head = insertNode(head, 6 ) Â
    k = 2 Â
    # Function call to perform the     # given operations     KSum(head, k) Â
    # print the linked list     Print (head) Â
# This code is contributed by # sanjeev2552 |
C#
// C# program for SP - K Sum using System; Â
// structure for linked list public class Node { Â Â Â Â public int data; Â Â Â Â public Node next; Â Â Â Â public Node( int key) Â Â Â Â { Â Â Â Â Â Â Â Â data = key; Â Â Â Â Â Â Â Â next = null ; Â Â Â Â } } Â
public class GFG { Â Â Â Â Â // allocated new node static Node head; Â
// function to insert node // in a Linked List public static Node insertNode(Node head, int key) {     if (head == null )         head = new Node(key);     else         head.next = insertNode(head.next, key); Â
    return head; } Â
// traverse the node // to print it public static void print(Node head) {     // traverse the linked list     while (head != null )     {         Console.Write(head.data + " " );         head = head.next;     }     Console.WriteLine(); } Â
// function to perform // the following operation public static void KSum(Node head, int k) {     // initially pointing     // to start     Node temp = head; Â
    // iterate till end     while (temp != null )     { Â
        // dummy variable         // to store k         int count = k; Â
        // summation of nodes         int sum = 0; Â
        // currently at node from         // which iteration is done         Node curr = temp; Â
        // till k nodes are visited and         // last node is not visited         while (count > 0 && curr != null )         {             // add to sum the node data             sum = sum + curr.data; Â
            // move to the next node             curr = curr.next;             count--;         } Â
        // change pointer's data         // of temp to sum         temp.data = sum; Â
        // move temp to         // next pointer         temp.next = curr; Â
        // move temp to         // the next pointer         temp = temp.next;     }     // return temp; } Â
// Driver Code public static void Main() { Â Â Â Â head = null ; Â
    // inserts nodes in     // the linked list     head = insertNode(head, 1);     head = insertNode(head, 2);     head = insertNode(head, 3);     head = insertNode(head, 4);     head = insertNode(head, 5);     head = insertNode(head, 6); Â
    int k = 2;          // Function call to perform     // the given operations     KSum(head, k); Â
    // print the linked list     print(head); } } Â
/* This code contributed by PrinciRaj1992 */ |
Javascript
<script>       // JavaScript program for SP - K Sum       // structure for linked list       class Node       {         constructor(key)         {           this .data = key;           this .next = null ;         }       } Â
      // allocated new node       var head = null ; Â
      // function to insert node       // in a Linked List       function insertNode(head, key)       {         if (head == null ) head = new Node(key);         else head.next = insertNode(head.next, key); Â
        return head;       } Â
      // traverse the node       // to print it       function print(head)       {                // traverse the linked list         while (head != null )         {           document.write(head.data + " " );           head = head.next;         }         document.write( "<br>" );       } Â
      // function to perform       // the following operation       function KSum(head, k)       {                // initially pointing         // to start         var temp = head; Â
        // iterate till end         while (temp != null )         {                    // dummy variable           // to store k           var count = k; Â
          // summation of nodes           var sum = 0; Â
          // currently at node from           // which iteration is done           var curr = temp; Â
          // till k nodes are visited and           // last node is not visited           while (count > 0 && curr != null )           {                        // add to sum the node data             sum = sum + curr.data; Â
            // move to the next node             curr = curr.next;             count--;           } Â
          // change pointer's data           // of temp to sum           temp.data = sum; Â
          // move temp to           // next pointer           temp.next = curr; Â
          // move temp to           // the next pointer           temp = temp.next;         }                  // return temp;       } Â
      // Driver Code       head = null ; Â
      // inserts nodes in       // the linked list       head = insertNode(head, 1);       head = insertNode(head, 2);       head = insertNode(head, 3);       head = insertNode(head, 4);       head = insertNode(head, 5);       head = insertNode(head, 6); Â
      var k = 2; Â
      // Function call to perform       // the given operations       KSum(head, k); Â
      // print the linked list       print(head);              // This code is contributed by rdtank.     </script> |
3 7 11
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!