o1-mini-2024-09-12· OpenAI
WildChat-4.8M (AI2)
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
always write short code short variable name highly optimized no explanation unique code
- Assistant
class Solution: def sumOfLastN_Nodes(self, h, n): f, s = h, h for _ in range(n): f = f.next while f: f = f.next s = s.next total = 0 while s: total += s.data s = s.next return total