wood burning stoves 2.0*
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
Author

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... ?


Nandish
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

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 7 API documentation
Scala Notes - My blog about Scala
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
Bartender

Joined: Oct 02, 2003
Posts: 11160
    
  16

"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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Nth Node from Last ???
 
Similar Threads
ParserImpl for DOM
Creating Linked List
Polynomial Linked List Reverse
Java Linked List
A doubt about Xpath expression