Lesson 8 of 14
Nth Node
Getting the Nth Node
To get the node at index k (0-indexed), advance a pointer k times from the head:
struct Node *nth_node(struct Node *head, int k) {
struct Node *cur = head;
while (k > 0 && cur != NULL) {
cur = cur->next;
k--;
}
return cur;
}
Returns a pointer to the node, or NULL if k is out of bounds.
Example
[10] -> [20] -> [30] -> [40] -> NULL
nth_node(head, 0) → [10] (head)
nth_node(head, 2) → [30]
nth_node(head, 9) → NULL (out of bounds)
O(n) Access
This is the "random access" cost of linked lists. Unlike arrays, there is no pointer arithmetic shortcut — you must walk the list each time.
This is why linked lists are poor choices when you frequently need elements by index.
Your Task
Implement struct Node *nth_node(struct Node *head, int k) that returns the node at index k, or NULL if out of bounds.
TCC compiler loading...
Loading...
Click "Run" to execute your code.