|
| 1 | +/* |
| 2 | +Nth node from end of linked list |
| 3 | +================================ |
| 4 | +
|
| 5 | +Given a linked list consisting of L nodes and given a number N. The task is to find the Nth node from the end of the linked list. |
| 6 | +
|
| 7 | +Example 1: |
| 8 | +Input: |
| 9 | +N = 2 |
| 10 | +LinkedList: 1->2->3->4->5->6->7->8->9 |
| 11 | +Output: 8 |
| 12 | +Explanation: In the first example, there |
| 13 | +are 9 nodes in linked list and we need |
| 14 | +to find 2nd node from end. 2nd node |
| 15 | +from end os 8. |
| 16 | +
|
| 17 | +Example 2: |
| 18 | +Input: |
| 19 | +N = 5 |
| 20 | +LinkedList: 10->5->100->5 |
| 21 | +Output: -1 |
| 22 | +Explanation: In the second example, there |
| 23 | +are 4 nodes in the linked list and we |
| 24 | +need to find 5th from the end. Since 'n' |
| 25 | +is more than the number of nodes in the |
| 26 | +linked list, the output is -1. |
| 27 | +Your Task: |
| 28 | +The task is to complete the function getNthFromLast() which takes two arguments: reference to head and N and you need to return Nth from the end or -1 in case node doesn't exist.. |
| 29 | +
|
| 30 | +Note: |
| 31 | +Try to solve in single traversal. |
| 32 | +
|
| 33 | +Expected Time Complexity: O(N). |
| 34 | +Expected Auxiliary Space: O(1). |
| 35 | +
|
| 36 | +Constraints: |
| 37 | +1 <= L <= 103 |
| 38 | +1 <= N <= 103 |
| 39 | +*/ |
| 40 | + |
| 41 | +int getNthFromLast(Node *head, int n) |
| 42 | +{ |
| 43 | + Node *main_ptr = head; |
| 44 | + Node *ref_ptr = head; |
| 45 | + |
| 46 | + int count = 0; |
| 47 | + if (head != NULL) |
| 48 | + { |
| 49 | + while (count < n) |
| 50 | + { |
| 51 | + if (ref_ptr == NULL) |
| 52 | + return -1; |
| 53 | + ref_ptr = ref_ptr->next; |
| 54 | + count++; |
| 55 | + } |
| 56 | + |
| 57 | + if (ref_ptr == NULL) |
| 58 | + { |
| 59 | + head = head->next; |
| 60 | + if (head != NULL) |
| 61 | + return (main_ptr->data); |
| 62 | + } |
| 63 | + else |
| 64 | + { |
| 65 | + while (ref_ptr != NULL) |
| 66 | + { |
| 67 | + main_ptr = main_ptr->next; |
| 68 | + ref_ptr = ref_ptr->next; |
| 69 | + } |
| 70 | + return (main_ptr->data); |
| 71 | + } |
| 72 | + } |
| 73 | + return -1; |
| 74 | +} |
0 commit comments