1014. Traversal in Linked List

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.

Example 1:

Input: linkedList = [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.

Example 2:

Input: linkedList = [1]

Output: [1]

Explanation:

Only one node (head) present in the list.

Now Your Turn!

Pick the correct output for the given input

Input: linkedList = [0, 2, 5]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

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

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/*
Definition of singly linked list:
class ListNode{
public:
int data;
ListNode *next;
ListNode() : data(0), next(nullptr) {}
ListNode(int x) : data(x), next(nullptr) {}
ListNode(int x, ListNode *next) : data(x), next(next) {}
};
*/
 
class Solution {
public:
vector<int> LLTraversal(ListNode *head) {
 
}
};
Test Case

Input:

Linked List