oneby7

Linked Lists Doubly linked lists

275. Build a Doubly Linked List from an Array

Medium

You are given an array values. Build a doubly linked list that holds the values in the same order, and return its head. The head holds values[0], the node after it holds values[1], and so on. If values is empty, return null.

A doubly linked list is a chain of nodes in which each node has a value and two pointers. next points to the following node, and prev points to the node before it. The head's prev is null, and the last node's next is null. The comment at the top of the starter code shows the node in your language.

The output shows the list you return as its values from the head on, so [4,1,6] is the list 4 ⇄ 1 ⇄ 6, and [] is null. The judge also checks every prev pointer. If one is wrong, the output names the first node whose prev is wrong, counting the head as node 1, instead of the values.

Example 1

Input: values = [9, -4, 9, 0, 3]

Output: [9,-4,9,0,3]

Explanation: The head holds 9 and its prev is null. Each later node's prev points to the node before it, so the node holding -4 points back to the head. The node holding 3 is last, and its next is null.

Example 2

Input: values = [1000000000]

Output: [1000000000]

Explanation: One node is both the head and the last node. Its prev and next are both null.

Example 3

Input: values = []

Output: []

Explanation: There are no values, so there are no nodes, and the function returns null.

Check your understanding

Work out the answer for this input before you write any code.

values = [3, 8, 1]

Constraints

  • 0 ≤ values.length ≤ 105
  • -109 ≤ values[i] ≤ 109

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.