Find the sum of last n nodes of the given Linked List

2

Given a linked list and a number n. Find the sum of last n nodes of the linked list.

Constraints: 0 <= n <= number of nodes in the linked list.

Examples:

Input : 10->6->8->4->12, n = 2
Output : 16
Sum of last two nodes:
12 + 4 = 16

Input : 15->7->9->5->16->14, n = 4
Output : 44

Method 1: (Recursive approach using system call stack)
Recursively traverse the linked list up to the end. Now during return from the function calls, add up the last n nodes. The sum can be accumulated in some variable passed by reference to the function or to some global variable.

// C++ implementation to find the sum of
// last 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};

// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;

    /* put in the data  */
    new_node->data = new_data;

    /* link the old list to the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

// function to recursively find the sum of last
// 'n' nodes of the given linked list
void sumOfLastN_Nodes(struct Node* head, int* n,
                                      int* sum)
{
    // if head = NULL
    if (!head)
        return;

    // recursively traverse the remaining nodes
    sumOfLastN_Nodes(head->next, n, sum);

    // if node count 'n' is greater than 0
    if (*n > 0) {

        // accumulate sum
        *sum = *sum + head->data;

        // reduce node count 'n' by 1
        --*n;
    }
}

// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;

    int sum = 0;

    // find the sum of last 'n' nodes
    sumOfLastN_Nodes(head, &n, &sum);

    // required sum
    return sum;
}

// Driver program to test above
int main()
{
    struct Node* head = NULL;

    // create linked list 10->6->8->4->12
    push(&head, 12);
    push(&head, 4);
    push(&head, 8);
    push(&head, 6);
    push(&head, 10);

    int n = 2;
    cout << "Sum of last " << n << " nodes = "
         << sumOfLastN_NodesUtil(head, n);
    return 0;
}

Output:

Sum of last 2 nodes = 16

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), if system call stack is being considered.

Method 2 (Iterative approach using user defined stack)
It is an iterative procedure to the recursive approach explained in Method 1 of this post. Traverses the nodes from left to right. While traversing pushes the nodes to a user defined stack. Then pops the top n values from the stack and adds them.

// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};

// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;

    /* put in the data  */
    new_node->data = new_data;

    /* link the old list to the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;

    stack<int> st;
    int sum = 0;

    // traverses the list from left to right
    while (head != NULL) {

        // push the node's data onto the stack 'st'
        st.push(head->data);

        // move to next node
        head = head->next;
    }

    // pop 'n' nodes from 'st' and
    // add them
    while (n--) {
        sum += st.top();
        st.pop();
    }

    // required sum
    return sum;
}

// Driver program to test above
int main()
{
    struct Node* head = NULL;

    // create linked list 10->6->8->4->12
    push(&head, 12);
    push(&head, 4);
    push(&head, 8);
    push(&head, 6);
    push(&head, 10);

    int n = 2;
    cout << "Sum of last " << n << " nodes = "
         << sumOfLastN_NodesUtil(head, n);
    return 0;
}

Output:

Sum of last 2 nodes = 16

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(n), stack size

Method 3 (Reversing the linked list)
Following are the steps:

  1. Reverse the given linked list.
  2. Traverse the first n nodes of the reversed linked list.
  3. While traversing add them.
  4. Reverse the linked list back to its original order.
  5. Return the added sum.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};

// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;

    /* put in the data  */
    new_node->data = new_data;

    /* link the old list to the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

void reverseList(struct Node** head_ref)
{
    struct Node* current, *prev, *next;
    current = *head_ref;
    prev = NULL;

    while (current != NULL) {
        next = current->next;
        current->next = prev;
        prev = current;
        current = next;
    }

    *head_ref = prev;
}

// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;

    // reverse the linked list
    reverseList(&head);

    int sum = 0;
    struct Node* current = head;

    // traverse the 1st 'n' nodes of the reversed
    // linked list and add them
    while (current != NULL && & n--) {

        // accumulate node's data to 'sum'
        sum += current->data;

        // move to next node
        current = current->next;
    }

    // reverse back the linked list
    reverseList(&head);

    // required sum
    return sum;
}

// Driver program to test above
int main()
{
    struct Node* head = NULL;

    // create linked list 10->6->8->4->12
    push(&head, 12);
    push(&head, 4);
    push(&head, 8);
    push(&head, 6);
    push(&head, 10);

    int n = 2;
    cout << "Sum of last " << n << " nodes = "
         << sumOfLastN_NodesUtil(head, n);
    return 0;
}

Output:

Sum of last 2 nodes = 16

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)

Method 4 (Using length of linked list)
Following are the steps:

  1. Calculate the length of the given Linked List. Let it be len.
  2. First traverse the (len – n) nodes from the beginning.
  3. Then traverse the remaining n nodes and while traversing add them.
  4. Return the added sum.
// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};

// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;

    /* put in the data  */
    new_node->data = new_data;

    /* link the old list to the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;

    int sum = 0, len = 0;
    struct Node* temp = head;

    // calculate the length of the linked list
    while (temp != NULL) {
        len++;
        temp = temp->next;
    }

    // count of first (len - n) nodes
    int c = len - n;
    temp = head;

    // just traverse the 1st 'c' nodes
    while (temp != NULL && & c--)

        // move to next node
        temp = temp->next;

    // now traverse the last 'n' nodes and add them
    while (temp != NULL) {

        // accumulate node's data to sum
        sum += temp->data;

        // move to next node
        temp = temp->next;
    }

    // required sum
    return sum;
}

// Driver program to test above
int main()
{
    struct Node* head = NULL;

    // create linked list 10->6->8->4->12
    push(&head, 12);
    push(&head, 4);
    push(&head, 8);
    push(&head, 6);
    push(&head, 10);

    int n = 2;
    cout << "Sum of last " << n << " nodes = "
         << sumOfLastN_NodesUtil(head, n);
    return 0;
}

Output:

Sum of last 2 nodes = 16

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)

Method 5 (Use of two pointers requires single traversal)
Maintain two pointers – reference pointer and main pointer. Initialize both reference and main pointers to head. First move reference pointer to n nodes from head and while traversing accumulate node’s data to some variable, say sum. Now move both pointers simultaneously until reference pointer reaches to the end of the list and while traversing accumulate all node’s data to sum pointed by the reference pointer and accumulate all node’s data to some variable, say temp, pointed by the main pointer. Now, (sum – temp) is the required sum of the last n nodes.

// C++ implementation to find the sum of last
// 'n' nodes of the Linked List
#include <bits/stdc++.h>
using namespace std;

/* A Linked list node */
struct Node {
    int data;
    struct Node* next;
};

// function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;

    /* put in the data  */
    new_node->data = new_data;

    /* link the old list to the new node */
    new_node->next = (*head_ref);

    /* move the head to point to the new node */
    (*head_ref) = new_node;
}

// utility function to find the sum of last 'n' nodes
int sumOfLastN_NodesUtil(struct Node* head, int n)
{
    // if n == 0
    if (n <= 0)
        return 0;

    int sum = 0, temp = 0;
    struct Node* ref_ptr, *main_ptr;
    ref_ptr = main_ptr = head;

    // traverse 1st 'n' nodes through 'ref_ptr' and
    // accumulate all node's data to 'sum'
    while (ref_ptr != NULL && & n--) {
        sum += ref_ptr->data;

        // move to next node
        ref_ptr = ref_ptr->next;
    }

    // traverse to the end of the linked list
    while (ref_ptr != NULL) {

        // accumulate all node's data to 'temp' pointed
        // by the 'main_ptr'
        temp += main_ptr->data;

        // accumulate all node's data to 'sum' pointed by
        // the 'ref_ptr'
        sum += ref_ptr->data;

        // move both the pointers to their respective
        // next nodes
        main_ptr = main_ptr->next;
        ref_ptr = ref_ptr->next;
    }

    // required sum
    return (sum - temp);
}

// Driver program to test above
int main()
{
    struct Node* head = NULL;

    // create linked list 10->6->8->4->12
    push(&head, 12);
    push(&head, 4);
    push(&head, 8);
    push(&head, 6);
    push(&head, 10);

    int n = 2;
    cout << "Sum of last " << n << " nodes = "
         << sumOfLastN_NodesUtil(head, n);
    return 0;
}

Output:

Sum of last 2 nodes = 16

Time Complexity: O(n), where n is the number of nodes in the linked list.
Auxiliary Space: O(1)

This article is contributed by Ayush Jauhari. 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 write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



2 Average Difficulty : 2/5.0
Based on 8 vote(s)










Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.