Given an arbitrary node in a doubly linked list, we can always reach the head by following the prev pointers. Once at the head, we can traverse the list in order using the next pointers to collect all values.
classSolution {
public: vector<int> toArray(Node* node) {
Node* head = node;
while (head->prev) head = head->prev;
vector<int> ans;
while (head) {
ans.push_back(head->val);
head = head->next;
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
functoArray(node*Node) []int {
head:=nodeforhead.Prev!=nil {
head = head.Prev }
ans:= []int{}
forhead!=nil {
ans = append(ans, head.Val)
head = head.Next }
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
public List<Integer>toArray(Node node) {
Node head = node;
while (head.prev!=null) head = head.prev;
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
12
classSolution {
funtoArray(node: Node?): List<Int> {
var head = node
while (head?.prev !=null) head = head.prev
val ans = mutableListOf<Int>()
while (head !=null) {
ans.add(head.`val`)
head = head.next
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
deftoArray(self, node: 'Optional[Node]') -> list[int]:
head = node
while head and head.prev:
head = head.prev
ans: list[int] = []
while head:
ans.append(head.val)
head = head.next
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnto_array(mut node: Option<Box<Node>>) -> Vec<i32> {
letmut head = node.as_ref();
whilelet Some(n) = head {
if n.prev.is_some() {
head = n.prev.as_ref();
} else {
break;
}
}
letmut ans = Vec::new();
letmut cur = head;
whilelet Some(n) = cur {
ans.push(n.val);
cur = n.next.as_ref();
}
ans
}
}