Here is the linked list. It looks like this.
In order to avoid the linear cost of insertion and deletion, we need to ensure that the list is not stored contiguously. By using this kind of list, we can make the cost of insertion and deletion be O(1).
The linked list consists of a series of structures, which are not necessarily adjacent in memory.
Each node contains the element and a pointer points to the next node, we call it Next pointer, And the last node’s Next pointer points to NULL. And ANSI C specifies that NULL is zero.
In my version, I put a head node to save the length of the linked list.
Now we can see the operations of LinkedList.
Operations
Insert
It’s the first step of the insert operation.
As we can see, we got Node A, B, C, and the C is the newest node we wanna insert into this list. First we make the Next pointer of C equals Next pointer of A, then the C node’s Next Pointer points to node B.
second step, we let the A’s Next pointer points to our new node C.
Finally, we finished it.
Insert Succeed!!
Let’s take a look at the code.
- Insert at the tail
1 | // Insert a value after all elements |
- Insert at given index
1 | // Insert a Value at the index you give |
Delete
We’ll show two steps of delete operation.
First step, we let the node A’s Next pointer equals the Next pointer of node C.
Because we just get one Next pointer for each node, so, it just make no pointer points to node C.
So delete Succeed!!
- Delete at the tail
1 | // Delete the last node of list L |
- Delete at the given index
1 | // Delete the node at the index you give |
Conclusion
We know that if you just calculate the cost of insertion or deletion, you’ll find T(n) = O(1).
But you know if we wanna insert or delete a value with specify index, it’ll cost O(n) in whole operation. But the cost of insertion or deletion still is O(1). Here, we just talk about the cost of insertion or deletion.