This post is completed by 1 user
|
Add to List |
28. Determine the Nth Node from the Tail in a Linked List
Objective: Given a linked list and integer 'n', write an algorithm to find the nth node from the end in the Linked List.
Example:
Original List : ->1->2->8->3->7->0->4 Output : 3rd Element from the end is : 7
Approach:
Recursive Approach:
- Recurse through the Linked list
- When we reach to the end of the list, base case will return 0
- Now with each passing back call through stack, add 1 and return.
- When count hits n, print the value.
Original List : ->1->2->8->3->7->0->4 Recursion::3rd Element from the end is : 7
Iterative Approach:
- Take two pointers approach
- Move the first pointer by n
- now move both the pointers and when the first pointer reaches the end of the list the second pointer will be at the nth node from the end.
- print the data
Original List : ->1->2->8->3->7->0->4 Recursion::3rd Element from the end is : 7