QUESTION: Return the Nth to last Element in a Single Linked List ?
Answer :
Example : Below is the Sample Linked List.
[0] [1] [2] [3] [4] ----> Direction1 -> 2 -> 3 -> 4 -> 5[4] [3] [2] [1] [0] <----- Direction.
Now return the Nth element from the end of the linked list.
i.e, if N = 2 /* Return 2nd Index element from the last. i.e., = 3 */
if N = 1 /* Return 4 that, it is 1st element from the last of list*/
if N = 3 /* return 2 that it is 3rd element from the last of linked list.*/
Solution :
Take 2 pointers one points to Head, and move the next pointer to n locations in linked list.
Example : if N = 3
Pointer 1 = points to Head.
Pointer 2 = points to element '4' in the linked list because that has the index = 3. in
the forward Direction.
Code :
Node *pointer2, * pointer1;pointer1 = head;while(i = 0 ; inext;
Now increment the both pointers by one by one when
when Pointer2 points to last element in the linked list, then the pointer 1 points to the nth element from the end of the list.
No comments:
Post a Comment