Arrays and linked lists are the foundation of data structures. Understanding them deeply is essential for every developer.
Arrays
Arrays provide O(1) access time but have fixed size.
Dynamic Arrays
typescript
class DynamicArray<T> {
private data: (T | undefined)[];
private size: number = 0;
private capacity: number;
constructor(capacity: number = 10) {
this.capacity = capacity;
this.data = new Array(capacity);
}
push(item: T) {
if (this.size === this.capacity) {
this.resize();
}
this.data[this.size++] = item;
}
private resize() {
const newCapacity = this.capacity * 2;
const newData = new Array(newCapacity);
for (let i = 0; i < this.size; i++) {
newData[i] = this.data[i];
}
this.data = newData;
this.capacity = newCapacity;
}
get(index: number): T | undefined {
if (index < 0 || index >= this.size) {
return undefined;
}
return this.data[index];
}
}Linked Lists
Linked lists provide dynamic sizing with O(1) insertions/deletions.
Singly Linked List
typescript
class ListNode<T> {
value: T;
next: ListNode<T> | null;
constructor(value: T) {
this.value = value;
this.next = null;
}
}
class LinkedList<T> {
private head: ListNode<T> | null = null;
private tail: ListNode<T> | null = null;
private length: number = 0;
append(value: T) {
const node = new ListNode(value);
if (!this.head) {
this.head = node;
this.tail = node;
} else {
this.tail!.next = node;
this.tail = node;
}
this.length++;
}
prepend(value: T) {
const node = new ListNode(value);
node.next = this.head;
this.head = node;
if (!this.tail) {
this.tail = node;
}
this.length++;
}
find(value: T): ListNode<T> | null {
let current = this.head;
while (current) {
if (current.value === value) {
return current;
}
current = current.next;
}
return null;
}
}When to Use Which?
Use arrays when:
- Fast access by index is needed
- Memory is constrained
- Data size is predictable
Use linked lists when:
- Frequent insertions/deletions
- Unknown data size
- Implementing other data structures
Conclusion
Arrays and linked lists each have their strengths. Choose based on your specific needs.