A friendly place for programming greenhorns!
Big Moose Saloon
Register / Login
Java in General
get fifth element from last linked list
Joined: Feb 15, 2005
Sep 26, 2007 11:35:00
Could anyone help me with a method for a Singly Linked List which gets fifth element from last linked list
I have the logic here:
1) have two ptrs. F_Ptr & S_Ptr.
2) Let the ptrs point to the START.
3) Take n as the offset.
4) Start traversing the S_Ptr after the F_Ptr after n.
suppose you want to find 5 element from the last of the list.
In the above case.
1) n = 5 // 5th element from the last
2) check atleast this many elements are there in the list before beginging
// traverse the F_Ptr offset for(;n!=0;n�,F_Ptr->next); // now set the S_Ptr to trail the F_Ptr S_Ptr = F_Ptr; for(;F_Ptr!=NULL; S_Ptr=F_Ptr; F_Ptr=F_Ptr->next) Now whe F_Ptr = Null, S_Ptr is just trailing behind right! it will be pointing to the n�th element from the last. When F_Ptr reaches end (i.e., F_Ptr is NULL) S_Ptr points to the 5th element from the last.
Joined: Oct 29, 2001
Sep 26, 2007 11:41:00
Please do not post
the same question
more than once. It causes confusion and duplication of effort as the community tries to help everyone.
How To Ask Questions On JavaRanch
It is sorta covered in the
JavaRanch Style Guide
subject: get fifth element from last linked list
Changing removeAt method to swap instead of removing
get fifth element from last for a Singly linked list
Ordered Doubly Linked List
need to implement stored moves in linked lists
Creating Linked List
All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter
| Powered by
Copyright © 1998-2014