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.

0


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.


Cpp Program Code:


The ListNode struct represents a node in the linked list, and the get_nth_node_from_end function takes a ListNode pointer head and an integer n as input, and returns an integer representing the value of the nth node from the end of the linked list.


The function initializes two pointers, p1 and p2, to the head node. It then moves p2 n nodes ahead of p1 by iterating through the linked list with a loop.


Once p2 is n nodes ahead of p1, the function moves both pointers until p2 reaches the end of the linked list. At this point, p1 is pointing to the nth node from the end of the linked list.


Finally, the function returns the value of the node pointed to by p1.


If n is larger than the length of the linked list, the function returns -1.


Python Program code:


The ListNode class represents a node in the linked list, and the get_nth_node_from_end function takes a ListNode object head and an integer n as input, and returns an integer representing the value of the nth node from the end of the linked list.


The function initializes two pointers, p1 and p2, to the head node. It then moves p2 n nodes ahead of p1 by iterating through the linked list with a loop.


Once p2 is n nodes ahead of p1, the function moves both pointers until p2 reaches the end of the linked list. At this point, p1 is pointing to the nth node from the end of the linked list.


Finally, the function returns the value of the node pointed to by p1.


If n is larger than the length of the linked list, the function returns -1.



Post a Comment

0Comments
Post a Comment (0)