Saturday, December 5, 2009

Reach i-th position from tail of link list

Question:

To reach i-th position from tail of link-list by traversing only once.

Example:

1-2-3-4-5-6-7-8-9

To reach 3rd node from tail. i.e Node 7

Answer:

-> Take two pointers.

-> Take first pointer to i-th position from head

-> Start incrementing both the pointers

-> When the first pointer reaches the tail, at that point second pointer will be pointing to i-th node from tail

Example:

1-2-3-4-5-6-7-8-9, to reach 3rd node from tail i.e. Node 7.

Tracing:

Step 1:

-> Pointer 1 & Pointer 2 points to node 1

Step 2:

-> Increment Pointer 1 '3' times, as we want 3rd node from tail

Step 3:

-> Increment both the pointers

Movement of Pointer 1: 3-4-5-6-7-8-9
Movement of Pointer 2: 1-2-3-4-5-6-7

Step 4:

Stop when Pointer 1 points to 9, at that time the Pointer 2 points to Node 7

Answer:

Node 7

No comments:

Post a Comment

Disclaimer:

The above post and all the posts in the blog are derived from facts, information, logical interpretation and logical conclusion of printed and internet materials available to me, perceived and produced by 99 gm brain of mine, which by no means always be accurate, consistent and complete.

All the posts are for personal quick reference only.

If any suggestion, correction, misinterpretation, misconception commented, which will be moderated and deleted if required, to avoid unforeseen issues.

If any trademark / copywrite issue is present, do send in a mail and appropriate tag (logo, name, website link) will be attached to the same.

Additional disclaimer will be attached wherever required in the post.