Problem
Given the head of a linked list, determine whether the length of the list is even or odd.
Examples
Example 1:
|
|
Example 2:
|
|
Solution
Method 1 - Slow and Fast Pointers
Use a 2x pointer( two nodes at a time). Take a pointer that moves at 2x. At the end, if the length is even, then the pointer will be NULL; otherwise it will point to the last node.
To solve this problem, we can use a fast pointer approach:
- Fast Pointer Traversal: Move the fast pointer two nodes at a time while checking if it reaches the end.
- Determine Length Parity:
- If the fast pointer reaches the end (
null
), the length is even. - If the fast pointer reaches a node and its next node is
null
, the length is odd.
- If the fast pointer reaches the end (
Code
|
|
|
|
Complexity
- ⏰ Time complexity:
O(n)
, wheren
is the number of nodes in the linked list. The list is traversed once. - 🧺 Space complexity:
O(1)
, since only a constant amount of extra space is used for the pointer.