Intuition & Alogorithm
Since it’s a singly linked list, we’d can only count the number of the node from head to tail. The equavalent question of this is remove the (N-n+1)-th node from the head of list and return its head, where N is the length of the list
. There are several corner cases to notice:
n > N or n <= 0
both conditions means we try to remove unexisted nodes in the list(before the head or after the end);n==N
this means we want to remove the head, we can deal with this one alone, or add a dummy node;
Besides corner cases, we should remember to use fast-slow pointer to remove a node from the list. (I’m used to call them current and previous pointer)
Code
1 | /** |
Complexity
Time Complexity: O(N+n) There are two for loops here, costing O(N) and O(n) respectively.
Space Complexity: O(1)