#include <iostream> using namespace std; struct Node { int data; Node* next; }; int main() { int arr[3] = {10, 20, 30}; cout << "Array addresses:\n"; for (int i = 0; i < 3; i++) { cout << &arr[i] << " "; } cout << "\nLinked list addresses:\n"; Node* n1 = new Node{10, nullptr}; Node* n2 = new Node{20, nullptr}; Node* n3 = new Node{30, nullptr}; n1->next = n2; n2->next = n3; Node* current = n1; while (current != nullptr) { cout << current << " "; current = current->next; } cout << endl; return 0; }
Arrays store elements in contiguous memory locations, so their addresses increase sequentially. Linked list nodes are allocated separately on the heap, so their addresses are scattered and not contiguous.
Each linked list node stores data plus a pointer to the next node, which adds extra memory overhead compared to arrays that store only data elements.
struct Node {
int data;
Node* next;
};
void printList(Node* head) {
while (head->next != nullptr) {
cout << head->data << " ";
head = head->next;
}
cout << head->data << endl;
}
int main() {
printList(nullptr);
return 0;
}The loop condition 'head->next != nullptr' causes the loop to stop before the last node. Then accessing 'head->data' outside the loop is safe only if head is not null. But if the list is empty or head is null, it causes a segmentation fault. Using 'while (head != nullptr)' safely traverses all nodes.
#include <iostream> using namespace std; struct Node { int data; Node* next; }; int main() { int arr[4] = {10, 20, 30, 0}; // Insert 15 at index 1 in array for (int i = 3; i > 1; i--) { arr[i] = arr[i-1]; } arr[1] = 15; cout << "Array after insertion: "; for (int i = 0; i < 4; i++) { cout << arr[i] << " "; } cout << endl; // Linked list: 10 -> 20 -> 30 Node n1 = {10, nullptr}; Node n2 = {20, nullptr}; Node n3 = {30, nullptr}; n1.next = &n2; n2.next = &n3; // Insert 15 after first node Node n_new = {15, nullptr}; n_new.next = n1.next; n1.next = &n_new; cout << "Linked list after insertion: "; Node* current = &n1; while (current != nullptr) { cout << current->data << " "; current = current->next; } cout << endl; return 0; }
In the array, elements from index 1 onwards shift right to make space for 15 at index 1. In the linked list, the new node with 15 is inserted after the first node, so the order becomes 10 -> 15 -> 20 -> 30.
Arrays store elements contiguously, allowing direct access by index. Linked lists store nodes scattered in memory, so to access the nth element, you must start at the head and follow pointers sequentially, which is slower.
