Linked List
Linked List
Arrays
● An array is a linear data structure that stores elements in contiguous memory locations.
● Each element can be accessed by its index in O(1) time (random access).
int main() {
vector<int> numbers;
numbers.push_back(10);
numbers.push_back(20);
numbers.push_back(30);
cout << "Size after push_backs: " << numbers.size() << endl;
return 0;
}
Advantages
● Automatic Resizing: No manual memory management required.
Disadvantages
● Reallocations: When capacity is exceeded, existing elements are copied/moved to a
new block.
● Linked List consists of nodes where each node contains a data field and a
reference(link) to the next node in the list
Node
● Stores the value and the reference to the next node.
The simplest linked list example
struct Node {
int data; // Value stored in the node
Node* next; // Pointer to the next node
● Doubly Linked List is when nodes have both previous and next node reference.
Why Linked List when you have Arrays?
Insertions and Deletions are inefficient Insertions and Deletions are efficient
● Otherwise
● And then make the next of new node as the next of previous node
● Finally, make the next of the previous node the new node
Deleting node at the beginning in linked list
● Make the second node as head
● Make the previous node next point to the next of the deleted node
Circular Linked Lists
● A circular linked list is a variation of the linked list where the last node links back to the
first node, forming a ring-like structure rather than ending with a nullptr.