Traversal in Linked List

Linked-List Fundamentals (Single LL) Easy

Given the head of a singly Linked List. Traverse the entire Linked List and return its elements in an array in the order of their appearance.

Examples:

Input: head -> 5 -> 4 -> 3 -> 1 -> 0

Output: [5, 4, 3, 1, 0]

Explanation: The nodes in the Linked List are 5 -> 4 -> 3 -> 1 -> 0, with the head pointing to node with value 5.

Input: head -> 1

Output: [1]

Explanation: Only one node present in the list.

Input: head -> 0 -> 2 -> 5

Constraints

  • 0 <= number of nodes in the Linked List <= 105
  • 0 <= ListNode.val <= 104

Hints

  • Start at the head node. Use a loop to traverse through each node of the linked list.
  • Initialize an empty array to store the values. Use a pointer to traverse the list. When the pointer becomes null or None, the traversal is complete.

Company Tags

Zoho Freshworks McKinsey & Company Splunk Robinhood Micron Technology Bain & Company MongoDB Philips Healthcare HCL Technologies American Express Uber OYO Rooms PwC AMD Cerner Broadcom ARM Walmart Ubisoft Etsy Teladoc Health Nutanix Alibaba Goldman Sachs TCS Cognizant Accenture Infosys Capgemini Wipro