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?
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!
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
//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.
Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.
Full documentation for every DigitalOcean product.
The Wave has everything you need to know about building a business, from raising funding to marketing your product.
Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.
New accounts only. By submitting your email you agree to our Privacy Policy
Scale up as you grow — whether you're running one virtual machine or ten thousand.
Sign up and get $200 in credit for your first 60 days with DigitalOcean.*
*This promotional offer applies to new accounts only.