#C11145. K-th Node from End of a Singly Linked List
K-th Node from End of a Singly Linked List
K-th Node from End of a Singly Linked List
You are given a singly linked list and an integer k. Your task is to find the k-th node from the end of the linked list.
If the linked list contains n nodes, then the k-th node from the end is the \( (n-k+1) \)th node from the beginning. If \( k > n \), print None
.
The solution should use the two-pointer technique to achieve an optimal time complexity.
inputFormat
The input is given through standard input (stdin) and consists of two lines:
- The first line contains two integers
n
andk
separated by a space, wheren
is the number of nodes in the linked list andk
is the position from the end you need to find. - The second line contains
n
space-separated integers representing the values of the nodes in the linked list. Ifn
is 0, this line will be empty.
outputFormat
Output a single line to standard output (stdout):
- The value of the k-th node from the end. If such a node does not exist (i.e. if
k
is greater than the length of the list), outputNone
.
5 2
1 2 3 4 5
4