Build a Linked List From an Array of Values
Solve this Problemnext) to the following node. The last node's next is null. Unlike an array, nodes aren't stored contiguously in memory — the only way to reach a given node is by following next pointers from the head. is built one node at a time, connected only through each node's next pointer. Given an array of integers vals, build a singly linked list containing those values in the same order, and return its head.
Each node in the list is a Node with two fields: val (the stored integer) and next (a pointer to the following node, or null if it's the last one). If vals is empty, return null — an empty list has no head.
Test Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
0 ≤ vals.length ≤ 10⁴ - ◆
-10⁹ ≤ vals[i] ≤ 10⁹ - ◆
Build the list in the same order as the array — vals[0] becomes the head
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
| 1 | class Solution { |
| 2 | public Node createLinkedList(int[] vals) { |
| 3 | Node dummy = new Node(0); |
| 4 | Node tail = dummy; |
| 5 | for (int v : vals) { |
| 6 | tail.next = new Node(v); |
| 7 | tail = tail.next; |
| 8 | } |
| 9 | return dummy.next; |
| 10 | } |
| 11 | } |
| 12 |
dummyCreate a throwaway dummy node so the first real node can be attached the same way as every later one. tail starts at dummy.
Approach & Solutions
Brute Force — Re-Traverse to Append Each Value
BruteFor each value, create a new node. If the list built so far is empty, that node becomes the head. Otherwise, walk all the way from the head to find the current last node, then attach the new node after it. Correct, but every append re-walks nodes that were already visited while appending the previous value.
O(n²)O(1) extra1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node createLinkedList(int[] vals) {
9 Node head = null;
10 for (int v : vals) {
11 Node newNode = new Node(v);
12 if (head == null) {
13 head = newNode;
14 } else {
15 Node curr = head;
16 while (curr.next != null) {
17 curr = curr.next;
18 }
19 curr.next = newNode;
20 }
21 }
22 return head;
23 }
24}Optimal — Tail Pointer, Single Pass
OptimalKeep a running pointer to the last node built so far — the tail — seeded with a throwaway dummy node so the very first real node doesn't need a special case. For each value, attach a new node right after tail and move tail forward to it. Every value is handled in O(1), so the whole list is built in a single O(n) pass.
O(n)O(1) extra1// Node definition used in this problem:
2// class Node {
3// int val;
4// Node next;
5// }
6
7class Solution {
8 public Node createLinkedList(int[] vals) {
9 Node dummy = new Node(0);
10 Node tail = dummy;
11 for (int v : vals) {
12 tail.next = new Node(v);
13 tail = tail.next;
14 }
15 return dummy.next;
16 }
17}