Traverse a Linked List and Collect Its Values
Implement traverseLinkedList
Given the
head of a singly linked list, visit every node in order and return an array of its values, head to tail.
Traversal is the operation nearly every other linked list algorithm is built on — search, length, printing, and copying all boil down to "visit each node once." Both the iterativeIterativeSolved with an explicit loop, keeping state (like a curr pointer) in local variables instead of the call stack. and recursiveRecursiveSolved by having the function call itself on a smaller version of the same problem — here, "collect the rest of the list" is the same problem as the original, just one node shorter. versions visit every node exactly once; the recursive version just spends extra call-stack space doing it.
Example 1:
Input: head = [10,20,30,40]
Output: [10,20,30,40]
Example 2:
Input: head = [5]
Output: [5]
Example 3:
Input: head = []
Output: []
+ 5 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes in head ≤ 10⁴ - ●
-10⁹ ≤ node value ≤ 10⁹ - ●
Traversing an empty list must return an empty array
head =
[10, 20, 30, 40]