Practice #5
Lesson 14 of 14 in Coddy's Linked List - Data Structures Series #5 course.
Challenge
EasyGiven an integer array arr (the values of a linked list) and a positive integer n, write a function nthFromEnd that returns the value of the n-th node from the end (1-indexed).
If n is out of bounds (zero, negative, or larger than the list), return -1.
Use a linked list to solve this problem! The classic two-pointer trick avoids a length-counting pass.
You must use the LinkedList class (provided in linkedlist.<ext> along with node.<ext>) — do not use language built-ins like arrays' built-in reverse, slicing, 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 = nthFromEnd(arr, len, n);
printf("%d\n", r);
return 0;
}