Bloomberg L.P. Interview Question: How would you print last n el... | Glassdoor

Interview Question

Financial Software Developer Interview(Student Candidate) New York, NY

How would you print last n elements of a linked list, n

  being small compared to size of linked list?
data structures

Interview Answer

3 Answers


Use an "output array" of n elements, populating it with elements encountered in the linked list. After the examining/saving the first n elements in the linked list, loop back to the beginning of the output array and start overwriting the existing values. Continue traversing/overwriting/looping to the end of the linked list. The output array will contain the last n values, with its index indicating the starting point from which you can print the last n values of the lined list..

Jerry on Oct 8, 2010

take two pointers to the linked list.

the first pointer points to the start, move the second pointer by n-steps. Now, move both pointers by one step each until the second pointer reaches the end. At this stage your first pointer will be pointing to the nth last element in the list. Simply print the value and keep moving the first pointer till the end.

anonymouse on Mar 11, 2011

One or more comments have been removed.
Please see our Community Guidelines or Terms of Service for more information.

Add Answers or Comments

To comment on this, Sign In or Sign Up.