Problem 291468 · easy · Level 02 Linear Data Structures

Value at Position k

linked list · traversal · indexing

Given the head of a singly linked list and an integer k, return the value of the k-th node counting from 1 (so k = 1 is the head). If there is no such node (k is less than 1 or larger than the length), return None.

Examples

Input:  head = 10 -> 20 -> 30, k = 2
Output: 20

Input:  head = 10 -> 20 -> 30, k = 4
Output: None

Constraints

  • 0 <= number of nodes <= 10**4
  • -10**4 <= k <= 10**4
  • Target: O(k) time, O(1) extra space; do not build a Python list of the values

Goals

  • Advance a pointer a fixed number of steps
  • Return None when the position does not exist
Starting Python…