Consider the following Python simulation of memory addresses for an array and a linked list. What will be the printed output?
class Node: def __init__(self, value): self.value = value self.next = None # Simulate memory addresses for array elements array = [1000, 1004, 1008, 1012] # Simulate linked list nodes with arbitrary addresses node1 = Node(1) node2 = Node(2) node3 = Node(3) node1.next = node2 node2.next = node3 # Simulated addresses for nodes addresses = {node1: 2000, node2: 3000, node3: 4000} print('Array memory addresses:') for addr in array: print(addr) print('Linked list node addresses:') for node in [node1, node2, node3]: print(addresses[node])
Remember arrays store elements in continuous memory locations, while linked list nodes can be scattered.
The array elements are stored in continuous memory addresses increasing by 4 bytes each. The linked list nodes have arbitrary addresses, not continuous.
Why do linked lists typically have nodes stored in non-contiguous memory locations compared to arrays?
Think about how memory is allocated when you add nodes to a linked list.
Linked lists allocate memory for each node separately at runtime, so nodes can be anywhere in memory, unlike arrays which use continuous blocks.
What is the output of the following code simulating access times for array and linked list?
import time # Simulate access times (in nanoseconds) array_access_times = [10, 10, 10, 10] linked_list_access_times = [10, 50, 90, 130] print('Array access times:') for t in array_access_times: print(t) print('Linked list access times:') for t in linked_list_access_times: print(t)
Arrays have constant access time; linked lists have increasing access time as you traverse nodes.
Array access times are constant because elements are contiguous. Linked list access times increase because each node is accessed by following pointers.
What error will occur when running this code simulating linked list memory addresses?
class Node: def __init__(self, value): self.value = value self.next = None node1 = Node(1) node2 = Node(2) node1.next = node2 addresses = {node1: 1000} print(addresses[node2])
Check if the dictionary contains the key you are trying to access.
The dictionary 'addresses' only has node1 as a key. Accessing addresses[node2] causes a KeyError because node2 is not a key.
Why do arrays generally have better cache performance compared to linked lists?
Think about how CPU caches work with continuous vs scattered memory.
Arrays store elements next to each other in memory, so when one element is accessed, nearby elements are loaded into cache, improving speed. Linked lists have nodes scattered, causing more cache misses.