Practice #2
Lesson 11 of 14 in Coddy's Doubly Linked List - Data Structures Series #6 course.
Challenge
EasyWrite a function sumLastN that gets an integer array arr (the values of a doubly linked list) and a positive integer n, and returns the sum of the last n elements.
If n is larger than the list, sum the whole list. If n is zero or negative, return 0.
Use a doubly linked list to solve this problem! Start at tail and walk backward n steps.
You must use the DoublyLinkedList class (provided in doublylinkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' reverse, slicing, sort, or stdlib list operations to compute the result.
Try it yourself
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "solution.h"
int main() {
char line1[8192];
char line2[64];
if (!fgets(line1, sizeof(line1), stdin)) line1[0] = '\0';
if (!fgets(line2, sizeof(line2), stdin)) line2[0] = '\0';
int arr[4096];
int len = 0;
char* tok = strtok(line1, " \t\r\n");
while (tok) { arr[len++] = atoi(tok); tok = strtok(NULL, " \t\r\n"); }
int n = atoi(line2);
int r = sumLastN(arr, len, n);
printf("%d\n", r);
return 0;
}