int[] arr = {1, 2, 3, 4, 5}; class Node { int value; Node next; Node(int val) { value = val; } } Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); head.next.next.next = new Node(4); head.next.next.next.next = new Node(5); // Access 4th element in array int arrayValue = arr[3]; // Access 4th element in linked list Node current = head; for(int i = 0; i < 3; i++) { current = current.next; } int listValue = current.value; System.out.println("Array 4th element: " + arrayValue); System.out.println("Linked List 4th element: " + listValue);
Arrays store elements in continuous memory blocks, so accessing any element by index is direct and fast. Linked lists store nodes scattered in memory, so accessing the 4th element requires traversing from the head node through 3 links, which is slower.
Each linked list node stores the data and a pointer to the next node, increasing memory usage compared to arrays which store only the data elements contiguously without extra pointers.
class Node { int value; Node next; Node(int val) { value = val; } } Node head = new Node(1); head.next = new Node(2); head.next.next = new Node(3); // Missing initialization for next pointer in Node constructor
In Java, object references default to null, so missing explicit initialization is not a problem. But in some languages or contexts, uninitialized pointers can cause unpredictable behavior. Here, the question tests understanding that next should be null to avoid dangling pointers.
int[] array = {10, 20, 30}; System.out.println("Array addresses:"); for (int i = 0; i < array.length; i++) { System.out.println("Address " + i + ": " + (1000 + i * 4)); } class Node { int value; Node next; Node(int v) { value = v; } } Node n1 = new Node(10); Node n2 = new Node(20); n1.next = n2; Node n3 = new Node(30); n2.next = n3; System.out.println("Linked list addresses:"); System.out.println("Node1: 5000"); System.out.println("Node2: 7000"); System.out.println("Node3: 9000");
The array elements are stored contiguously starting at address 1000 with 4 bytes per int, so addresses increase by 4. The linked list nodes are at arbitrary addresses 5000, 7000, and 9000, showing non-contiguous memory allocation.
CPU caches load blocks of contiguous memory (cache lines). Arrays store elements contiguously, so traversing them benefits from cache locality. Linked list nodes are scattered, so each node access may load a new cache line, causing more cache misses and slower traversal.
