Skip to content

3263. Convert Doubly Linked List to Array I 👍

  • Time: $O(n)$
  • Space: $O(1)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  vector<int> toArray(Node* head) {
    vector<int> ans;
    Node* curr = head;

    while (curr != nullptr) {
      ans.push_back(curr->val);
      curr = curr->next;
    }

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int[] toArray(Node head) {
    List<Integer> ans = new ArrayList<>();
    Node curr = head;

    while (curr != null) {
      ans.add(curr.val);
      curr = curr.next;
    }

    return ans.stream().mapToInt(Integer::intValue).toArray();
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
class Solution:
  def toArray(self, head: 'Optional[Node]') -> list[int]:
    ans = []
    curr = head

    while curr:
      ans.append(curr.val)
      curr = curr.next

    return ans