Given a single linked list, calculate the sum of the last n nodes. Note: It is…
- User
Given a single linked list, calculate the sum of the last n nodes.
Note: It is guaranteed that n <= number of nodes.
Examples:
Input: Linked List: 5->9->6->3->4->10, n =3
5
9
6
3
4
10
Output: 17 Explanation: The sum of the last three nodes in the linked list is 3 + 4 + 10 = 17.
Input: Linked List: 1->2, n = 2
1
2
Output: 3 Explanation: The sum of the last two nodes in the linked list is 2 + 1 = 3.
Constraints: 1 <= number of nodes, n <= 105 1 <= node->data <= 103
class Solution: def sumOfLastN_Nodes(self, head, n): #function should return sum of last n nodes
class Solution { public: /*Structure of the node of the linled list is as
codestruct 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 int sumOfLastN_Nodes(struct Node* head, int n) { // Code here }};
write two code one in python and second in c++ with different from first which is highly optimized and both code should be unique always write short code highly optimized no explanation unique code
- Assistantpython
class Solution: def sumOfLastN_Nodes(self, head, n): total, current = 0, head while current: total += current.data current = current.next window_sum, current = 0, head for _ in range(total - n): window_sum += current.data current = current.next return total - window_sumcppclass Solution { public: int sumOfLastN_Nodes(struct Node* head, int n) { int sum=0, count=0; Node* start = head; while(count < n){ sum += start->data; start = start->next; count++; } Node* ptr = head; while(start){ sum += ptr->data - (start->data); ptr = ptr->next; start = start->next; } return sum; } };