Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Tuesday, January 2, 2018

Sum of last n nodes Linkedlist


recursive approach:

int cnt=0,res=0;
void givesum(struct Node* head)
{
    if(head==NULL)
    return ;
    givesum(head->next);
    if(cnt-->0)
    res+= head->data;
    
}
int sumOfLastN_Nodes(struct Node* head, int n)
{
      // Code here
      cnt=n;
      res=0;
      givesum(head);
      return res;
}

0 Comments:

Post a Comment

Stats