Practice Problem Link: Linked List To Array
Please make sure to try solving the problem yourself before looking at the editorial.
Problem Statement
Given a Linked List, return an array containing the nodes of the list in the same order.
Approach
The idea is simply to traverse the given linked list and store each node value in the answer array and return the array.
Analysis
- Time Complexity:
O(n) - Auxiliary Space Complexity:
O(1)
Implementation
C++
/* This is the ListNode class definition
class ListNode {
public:
int data;
ListNode* next;
ListNode(int data) {
this->data = data;
this->next = NULL;
}
};
*/
vector<int> linkedListToArray (ListNode* head) {
vector<int> array;
ListNode* currentNode = head;
while (currentNode != NULL) {
array.push_back(currentNode->data);
currentNode = currentNode->next;
}
return array;
}Java
/** This is the ListNode class definition
class ListNode {
int data;
ListNode next;
ListNode(int data) {
this.data = data;
this.next = null;
}
}
**/
class Solution {
List<Integer> linkedListToArray (ListNode head) {
List<Integer> array = new ArrayList<Integer>();
ListNode currentNode = head;
while (currentNode != null) {
array.add(currentNode.data);
currentNode = currentNode.next;
}
return array;
}
}