Question

How to find the 3rd node from the end in a singly linked list?

How to find the 3rd node from the end in a singly linked list? i can not traverse the linked list again and i cannot traverse backward because it’s a singly linked list. So what do? This problem challenging For me please help?


Submit an answer

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Sign In or Sign Up to Answer

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

Want to learn more? Join the DigitalOcean Community!

Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in Q&A, subscribe to topics of interest, and get courses and tools that will help you grow as a developer and scale your project or business.

You have Singly Linked List given,and you have to write a function that returns the value at the n’th node from the end of the Linked List. Here is the solution: Now you are trying to find 3rd node from end of the linked list, So let’s take n=3. for example we have linked list A->B->C->D->null if you’ll give input n=3 then you’ll get output as ‘B’

Let’s take look at logic,

Method : Use length of linked list

  1. Calculate the length of Linked List. Let the length be len.
  2. Print the (len – n + 1)th node from the beginning of the Linked List.

//Java Solution

void printNthFromLast(int n) 
{ 
    int len = 0; 
    Node temp = head; 

    // 1) count the number of nodes in Linked List 
    while (temp != null) { 
        temp = temp.next; 
        len++; 
    } 

    // check if value of n is not more than length of 
    // the linked list 
    if (len < n) 
        return; 

    temp = head; 

    // 2) get the (len-n+1)th node from the beginning 
    for (int i = 1; i < len - n + 1; i++) 
        temp = temp.next; 

    System.out.println(temp.data); 
}

//printNthFromLast() function will calculate the length of linked list first,then using (len-n+1) formula it will give output for nth node from the end of linkedlist.