Traversal in Linked List

Linked-List Fundamentals (Single LL) Easy
  • Fun Fact: The problem of traversing a singly Linked List is very commonly used in software development
  • One of its real-world applications is found in web browser history
  • When you navigate the web, your browser keeps track of the websites you've visited using a form of linked list
  • Each site is a node in the list and you can move backwards and forwards through your history, much like traversing a linked list
  • Additionally, linked lists are also frequently used in the implementation of filesystems, where directories are often represented as singly linked lists, with each node representing a file or sub-directory

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