Simulate a Linked List with Iterator and Transform
Data Structure DesignAuto-graded · 18 test casesLast updated
Tests ability to implement a doubly-linked list supporting sequential iteration and non-mutating element-wise transformation via a command-driven simulation.
Linked List Command Simulator
You are given a sequence of commands to execute against a stateful doubly-linked list. Implement a function that processes each command in order and returns the list of results.
The Data Structure
Your simulation manages one doubly-linked list and one iterator at a time. Each command either modifies the list, creates an iterator, or queries the iterator.
Commands
| Command | Arguments | Behavior | Return value |
|---|---|---|---|
"append" | [val] | Add val to the end of the list | None |
"map" | [op, operand] | Replace the current list with a new one where every element has been transformed (see below). The original list is discarded. | The new list as a Python list |
"iterator" | [] | Create an iterator positioned at the first element of the current list | None |
"hasNext" | [] | Return True if the iterator has at least one more element, False otherwise | bool |
"next" | [] | Return the current element and advance the iterator. If there is no current element, return None | int or None |
Map Operations
The "map" command accepts an operation name and an integer operand:
"add"— addoperandto each element"multiply"— multiply each element byoperand
"map" always produces a new list and does not alter the prior list's nodes. After a "map", the active list is the new transformed list. Any existing iterator refers to the old list and is unaffected.
Simulation Rules
- The list starts empty.
- If
"hasNext"or"next"is called before any"iterator"command, treat it as if the iterator was created over an empty list:"hasNext"returnsFalseand"next"returnsNone. "map"on an empty list returns an empty Python list[].- Chained
"map"commands each operate on the result of the previous one.
Constraints
1 ≤ len(operations) == len(arguments) ≤ 500"append"values satisfy−10^6 ≤ val ≤ 10^6"map"operands satisfy−10^3 ≤ operand ≤ 10^3- The only map operations used are
"add"and"multiply" operationscontains only the five command strings defined above
Examples
Example 1
Input: simulate_linked_list(['append', 'append', 'map', 'iterator', 'hasNext', 'next', 'hasNext', 'next', 'hasNext'], [[1], [2], ['multiply', 2], [], [], [], [], [], []])
Output: [None, None, [2, 4], None, True, 2, True, 4, False]
Example 2
Input: simulate_linked_list(['iterator', 'hasNext', 'next', 'next'], [[], [], [], []])
Output: [None, False, None, None]
Example 3
Input: simulate_linked_list(['append', 'append', 'map', 'map'], [[3], [-2], ['add', 5], ['multiply', 2]])
Output: [None, None, [8, 3], [16, 6]]
Hints
Hint 1
Build the doubly-linked list with a Node class that stores prev and next pointers, and keep a tail pointer so append is O(1) without walking the list.
Hint 2
For the iterator, store just a cursor (a reference to the next node to return). hasNext checks whether the cursor is None; next returns the cursor's value and advances the cursor.
Hint 3
map should walk the current list with its own cursor, apply the transformation, and append each result into a brand-new list — never touching the original nodes.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The problem is really three smaller problems glued together by a command dispatcher.
1. The doubly-linked list
Each node holds a value plus prev and next pointers. The list itself tracks head and tail. Keeping tail means append never has to walk the list — it just links the new node after the current tail and updates the pointer, which is O(1).
2. The iterator
The iterator is a separate object with a single cursor field pointing to the next node to return. This keeps the traversal state completely outside the list, so multiple independent iterators over the same list never interfere. has_next is a single null-check. next_val reads the cursor's value, advances the cursor, and returns the value — all O(1).
3. map / apply_map
apply_map creates a fresh _DoublyLinkedList, walks the source list from head to None with its own local cursor, applies the arithmetic, and appends each result to the new list. It never touches the source nodes. After the command dispatcher calls apply_map, it replaces the active list reference with the new one. Any iterator that was created before the map still holds a cursor into the old list's nodes and is unaffected, which is exactly the specified behavior.
Command dispatcher
A simple loop zips operations with arguments and routes each pair to the right method. Results are accumulated in order and returned as a flat list.
Why it produces the correct outputs
appendalways adds to the tail, soto_list()produces elements in insertion order.mapchains correctly because each call replaceslinked_listin the dispatcher's local scope; the nextmapoperates on the already-transformed list.- An iterator created before a
mapkeeps its old cursor, sohasNext/nextkeep walking the pre-map data. - If no
iteratorcommand has been issued, the dispatcher passesNonethrough theif iterator is not Noneguard and returnsFalse/Noneas specified. mapon an empty list starts with an empty_DoublyLinkedListand the while loop body never executes, soto_list()returns[].
Complexity
| Operation | Time | Space |
|---|---|---|
append | O(1) | O(1) per node |
iterator | O(1) | O(1) |
hasNext / next | O(1) | O(1) |
map over n elements | O(n) | O(n) for the new list |
| Full simulation of m commands, list size ≤ n | O(m · n) worst case | O(n) |
Full reference solution
from typing import List
class _Node:
def __init__(self, value: int):
self.value = value
self.prev = None
self.next = None
class _DoublyLinkedList:
def __init__(self):
self.head = None
self.tail = None
def append(self, value: int) -> None:
node = _Node(value)
if self.tail is None:
self.head = self.tail = node
else:
node.prev = self.tail
self.tail.next = node
self.tail = node
def apply_map(self, operation: str, operand: int) -> "_DoublyLinkedList":
result = _DoublyLinkedList()
current = self.head
while current is not None:
if operation == "add":
new_val = current.value + operand
elif operation == "multiply":
new_val = current.value * operand
else:
raise ValueError(f"Unknown map operation: {operation}")
result.append(new_val)
current = current.next
return result
def make_iterator(self) -> "_LinkedListIterator":
return _LinkedListIterator(self.head)
def to_list(self) -> List[int]:
values = []
current = self.head
while current is not None:
values.append(current.value)
current = current.next
return values
class _LinkedListIterator:
def __init__(self, start):
self._cursor = start
def has_next(self) -> bool:
return self._cursor is not None
def next_val(self):
if self._cursor is None:
return None
value = self._cursor.value
self._cursor = self._cursor.next
return value
def simulate_linked_list(operations: List[str], arguments: List[List]) -> List[object]:
linked_list = _DoublyLinkedList()
iterator = None
results = []
for command, args in zip(operations, arguments):
if command == "append":
linked_list.append(args[0])
results.append(None)
elif command == "map":
linked_list = linked_list.apply_map(args[0], args[1])
results.append(linked_list.to_list())
elif command == "iterator":
iterator = linked_list.make_iterator()
results.append(None)
elif command == "hasNext":
results.append(iterator.has_next() if iterator is not None else False)
elif command == "next":
results.append(iterator.next_val() if iterator is not None else None)
else:
raise ValueError(f"Unknown command: {command}")
return results