File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Nth Node from Last ??? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Nth Node from Last ???" Watch "Nth Node from Last ???" New topic

Nth Node from Last ???

Nandish Sri
Ranch Hand

Joined: Jan 19, 2004
Posts: 45
How to find the N'th node from last, in a singly linked list .. ? You are given only the first node..

Any idea... ?

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 15081

Is this a homework question?

Do you understand how singly linked lists work?

Without immediately thinking about how to implement this in Java, what do you think yourself would be the steps to solve this?

Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 8 API documentation
Nandish Sri
Ranch Hand

Joined: Jan 19, 2004
Posts: 45
This is a question running in my mind.. I need the efficient logic.

my logic is... indexing the LL in an array and get the what Nth element in a shot.. But still this is inefficient . But, How to find the Nth Node from Last in a single traversal... ?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

"Nandish KB",

Somebody probably should have mentioned it sooner, but your name does not quite meet our Naming policy. You need a real sounding first AND last name (although initials for a first name are allowed). We'd appreciate it if you'd change it by going here.

Now, about your question...

forget about java for a minute. if i said to you "i'm going to recite some numbers. when i'm done, tell me the 13th from last one", how would you do it? think about what you need to remember, and what you can forget, and when.

write out the steps you'd take on paper, or post them here, and we'll be happy to review them with you. Once you have that, writing the code is much easier.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: Nth Node from Last ???
It's not a secret anymore!