Given a slice of values, build a singly linked list containing those values in order and return its head.
createLinkedList(values)
Input format: space-separated values. Output the resulting list (or empty line for an empty input).
[1, 2, 3] // → 1 → 2 → 3
[9] // → 9
[] // → (empty)
Building a list from values sounds trivial, but there's a bookkeeping trap: the first node you create has nothing to attach to yet. If your rule is always "attach after the current tail," you need a tail before you've built anything — including before the first node exists.
Invent a placeholder node that represents no real value, and treat it as sitting right before the list starts. Now every value, including the first, follows the same rule: create a node, attach it after the current tail, move the tail forward. No special case for the first element — the dummy absorbs it.
tail to it.tail.next, move tail to the new node.dummy.next — the real head, skipping the placeholder.Without the dummy, you'd need an "is this the first node?" check every iteration, or separate logic for setting the head versus appending. The dummy trades that conditional complexity for one throwaway node — cheap and uniform. Whenever you catch yourself writing "if this is the first item, do X, otherwise Y," consider a dummy node instead so X and Y become the same code path.
Each value costs constant work — allocate a node, relink two pointers — so it's O(n) time and O(n) space for the resulting list.
def create_linked_list(values):
dummy = ListNode(0)
tail = dummy
for v in values:
tail.next = ListNode(v)
tail = tail.next
return dummy.next
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.