The key idea is to traverse the doubly linked list from the head node, collecting each node’s value in order into an array. Since the list is doubly linked, we only need to follow the next pointers for this task.
functoArray(head*Node) []int {
ans:= []int{}
forhead!=nil {
ans = append(ans, head.Val)
head = head.Next }
returnans}
1
2
3
4
5
6
7
8
9
10
classSolution {
public List<Integer>toArray(Node head) {
List<Integer> ans =new ArrayList<>();
while (head !=null) {
ans.add(head.val);
head = head.next;
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
funtoArray(head: Node?): List<Int> {
val ans = mutableListOf<Int>()
var node = head
while (node !=null) {
ans.add(node.`val`)
node = node.next
}
return ans
}
}
1
2
3
4
5
6
7
classSolution:
deftoArray(self, head: 'Optional[Node]') -> list[int]:
ans: list[int] = []
while head:
ans.append(head.val)
head = head.next
return ans
1
2
3
4
5
6
7
8
9
10
impl Solution {
pubfnto_array(mut head: Option<Box<Node>>) -> Vec<i32> {
letmut ans = Vec::new();
whilelet Some(node) = head {
ans.push(node.val);
head = node.next;
}
ans
}
}