Which statement best describes the memory layout difference between an array and a linked list?
Think about how elements are stored physically in memory for each data structure.
Arrays allocate a block of memory where all elements are stored one after another. Linked lists allocate nodes anywhere in memory and use pointers to connect them.
Consider the following C# code snippets. What is the output of accessing the third element in each data structure?
int[] arr = {10, 20, 30, 40}; class Node { public int val; public Node next; public Node(int v) { val = v; next = null; } } Node head = new Node(10); head.next = new Node(20); head.next.next = new Node(30); head.next.next.next = new Node(40); Console.WriteLine(arr[2]); Console.WriteLine(head.next.next.val);
Remember array indexing starts at 0 and linked list traversal uses next pointers.
arr[2] accesses the third element in the array which is 30. head.next.next.val accesses the third node's value which is also 30.
What error will occur when running the following C# code that tries to insert a new node after the head?
class Node { public int val; public Node next; public Node(int v) { val = v; next = null; } } Node head = new Node(1); Node newNode = new Node(2); newNode.next = head.next; head.next = newNode; Console.WriteLine(head.next.next.val);
Check if head.next is initialized before accessing head.next.next.
Initially head.next is null, so newNode.next = head.next sets newNode.next to null. Then head.next = newNode. Accessing head.next.next.val tries to access null.val causing NullReferenceException.
Given an array and a linked list each storing 3 integers, which data structure uses more memory and why?
int[] arr = new int[3] {1, 2, 3}; class Node { public int val; public Node next; public Node(int v) { val = v; next = null; } } Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3);
Consider the extra space needed for pointers in linked list nodes.
Each linked list node stores an integer and a pointer to the next node, increasing memory usage compared to array elements which store only integers.
Why do arrays generally have better cache performance than linked lists?
Think about how CPU cache works with contiguous memory blocks.
Arrays store elements next to each other, so CPU cache can load a block of elements efficiently. Linked lists have nodes scattered in memory, causing frequent cache misses and slower access.
