Linked list
A linked list is a data structure that consists of nodes, where each node has a value and a link to the next node.
Compared to arrays, the elements are not necessarily stored contiguously. That means inserting or deleting an element does not require moving other elements, but you cannot access an element by index in constant time.
Time complexity
| operation | time |
|---|---|
| insert after a known node | |
| delete after a known node | |
| search for a value |
Implementation
Search for a value
Given the head of a linked list and a value, check if the value is in the list.
Start at the head and follow next until the value is found or the pointer is empty.
In the worst case every node is visited once, so it takes time.
Insert a node
Given a node of a linked list, insert a new node with a given value right after the given node.
Create the new node pointing to the node after the given one, then point the given node to the new node. Only two pointers change and nothing else in the list moves, so it takes time.
Delete a node
Given a node of a linked list, delete the node right after it.
Point the given node to the node after the next one. Only one pointer changes and nothing else in the list moves, so it takes time.
Build it
Implement contains, insert_after and delete_after in the class below.
For the insert and delete we have to find the node first, so the time complexity will be O(n).