Improve Article
Save Article
Like Article
Given a Linked List and a number N, write a function that returns the value at the Nth node from the end of the Linked List. Examples: Input: 1 -> 2 -> 3 -> 4, N = 3 Input: 35 -> 15 -> 4 -> 20, N = 4 Naive Approach: Follow the given steps to solve the problem using this approach:
Below is the implementation of the above approach:
Time complexity: O(M) where M is the size of the linked list Below is a recursive code for the same method. Thanks to Anuj Bansal for providing the following code.
Time Complexity: O(M) where M is the length of the linked list. Nth node from the end of a Linked List using two pointers:
Below image is a dry run of the above approach: Follow the given steps to solve the problem:
Below is the implementation of the above approach:
Output35->15->4->20->NULL Node no. 4 from end is: 35 Time Complexity: O(M) where M is the length of the linked list. Please write comments if you find the above codes/algorithms incorrect, or find other ways to solve the same problem. |