Find the Sum of Last N nodes of the Linked List | EASY | GFG POTD | 23-10-24| GFG Problem of the day
ฝัง
- เผยแพร่เมื่อ 5 พ.ย. 2024
- #geeksforgeeks #problemoftheday #cpp #datastructures #potd #potdgfgtoday #gfg #gfgsolutions #gfgstreek #cpp #python #javascript #java #javaprogramming #datastructures #algorithm #algorithms #pythonprogramming #coding #programming #problemsolving #problemsolved
Geeks for Geeks Problem of the Day(POTD) in C++ | Find the Sum of Last N nodes of the Linked List
| Full code Available :👇
GitHub 🔗: UdaySharmaGitHub
Repository Name: GFG-Problems
It would be helpful, if you can upload leetcode potd solving videos
Sure bro✨
class Solution {
public:
/*Structure of the node of the linled list is as
struct Node {
int data;
struct Node* next;
Node(int x){
data = x;
next = NULL;
}
};
*/
// your task is to complete this function
// function should return sum of last n nodes
// reverse
Node* reverse(Node* head){
Node* curr = head , *prev = nullptr , *nxt = nullptr;
while(curr){
nxt = curr->next;
curr->next = prev;
prev = curr;
curr = nxt;
}
return prev;
}
int sumOfLastN_Nodes(struct Node* head, int n) {
// Code here
head = reverse(head);
long int ans = 0;
while(n-- && head){ // n decreamenet // 3 2 1 0
ans += head->data;
head = head ->next;
}
return ans;
}
};