Search⌘ K
AI Features

Solution Review: Return the Nth Node From The End

Learn how to return the nth node from the end of a singly linked list using two approaches: a double iteration method that calculates list length and a more efficient two-pointer technique that finds the node in a single pass. Understand their time complexities and implementation details to solve linked list challenges effectively.

Solution 1: Double iteration

C#
using System;
namespace chapter_3
{
class Challenge_10
{
static void Main(string[] args)
{
LinkedList list = new LinkedList(); //creating list
for (int j = 0; j <= 7; j++)
{
list.InsertAtHead(j); //insertng data in list
list.PrintList();
}
int num = 5;
int nth = list.FindNth(num); // calling findNth function of the list
Console.WriteLine(num + "th element from end of the list : " + nth);
return;
}
}
}

In this approach, the main goal is to figure out the index of the node you need to reach. The algorithm follows these simple steps:

  1. Calculate the length of the linked list.
  2. Check if n is within the length.
...