Think about which data structure allows easy insertion and deletion without shifting many elements.
Linked lists allow fast insertion and deletion anywhere because they only change pointers, unlike arrays which require shifting elements.
int[] arr = {10, 20, 30, 40}; // Insert 99 at index 2 in array (simulate by shifting) int[] newArr = new int[arr.length + 1]; for (int i = 0; i < 2; i++) newArr[i] = arr[i]; newArr[2] = 99; for (int i = 2; i < arr.length; i++) newArr[i+1] = arr[i]; // Linked list: 10 -> 20 -> 30 -> 40 // Insert 99 after second node // Resulting list: 10 -> 20 -> 99 -> 30 -> 40
Remember array insertion requires shifting elements after the insertion point.
Inserting 99 at index 2 in the array shifts elements from index 2 onward right by one. The linked list insertion just changes pointers to insert 99 after the second node.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } Node head = new Node(1); head.next = new Node(2); Node current = head; while (current.next != null) { System.out.println(current.data); current = current.next.next; }
Look at how current moves in the loop and what happens when it reaches the end.
The code moves current by two nodes each iteration but checks only current.next != null. When current.next is the last node, current.next.next is null, so current becomes null and next iteration causes NullPointerException.
int[] arr = {10, 20, 30, 40}; // Remove 20 from array by shifting int[] newArr = new int[arr.length - 1]; int indexToRemove = 1; for (int i = 0, j = 0; i < arr.length; i++) { if (i != indexToRemove) { newArr[j++] = arr[i]; } } // Linked list: 10 -> 20 -> 30 -> 40 // Remove node with data 20 // Resulting list: 10 -> 30 -> 40
Think about how elements shift in arrays and how nodes are removed in linked lists.
Removing 20 from the array shifts elements after index 1 left by one. Removing node 20 in linked list changes the next pointer of node 10 to node 30.
Consider memory fragmentation and overhead of pointers in linked lists.
Arrays use contiguous memory which avoids fragmentation and have less overhead per element. Linked lists use extra memory for pointers and can cause fragmentation. For limited memory and fragmentation concerns, arrays are better despite costly insertions.
