Understanding insertion after the given node
Inserting after a given node in a singly linked list is a relatively straightforward operation. Unlike arrays, we can insert data at any point in a linked list without recreating the entire list. When inserting after a node in a linked list, there are two cases to consider.
1. The list is empty
If the list is empty and contains no elements, we cannot find the given node because it does not exist within the list. Inserting a new node after the given node is not possible because there is no reference point within the list to perform the insertion. In such a case, the method would return without making any changes.
The list is empty
Algorithm
- Step 1: Return from the function.
2. The list is not empty
Since the new node will be inserted between two existing nodes, we must ensure that we properly set up the next pointers of these nodes. Inserting after a given node is a three-step process.
The list is not empty
Algorithm
- Step 1: Create a new node with the given data.
- Step 2: Set the `next` pointer of the new node to hold the node's reference stored in the `next` pointer of the `given` node.
- Step 3: Set the `next` pointer of the `given` node to hold the reference of the new node.
Implementation
We will be given the node, after which we will perform the insertion. When implementing the logic for the operation, we consider both possible cases and write the code for each in conditional blocks.
C++
Java
Typescript
Javascript
Python
next pointer of the given node. If we modify the given node first, we will lose the reference to the next node in the chain.Complexity Analysis
The time complexity of the above function is not affected by the length of the linked list because it only involves inserting a new node after the given node and performing pointer manipulations around the given node. Since these operations take constant time, the function's time complexity is O(1).
All cases: Insert after the given node
The function's space complexity is O(1) because it only creates a single new node and does not use any additional data structures.
Best Case
- Space Complexity - O(1)
- Time Complexity - O(1)
Worst Case
- Space Complexity - O(1)
- Time Complexity - O(1)