Problem Link - Optimal insertion at the end
Problem Statement:
By maintaining a tail pointer, which will point to the last element of the linked list. Thus whenever we want to insert at the end, we can use tail for that.
Task
Add a new tail pointer and update the current insertAtEnd to pass this exercise.
Approach:
The key idea of this solution is to efficiently insert elements at the end of the list using a tail pointer. By maintaining both the head
and tail
pointers, we can avoid traversing the entire list each time we want to add a new node, making the insertion process faster.
Here’s how the approach works:
-
Node Structure:
- A
Node
stores two things:- value: The data of the node.
- next: A pointer that points to the next node in the list (or
nullptr
if it’s the last node).
- A
-
LinkedList Class:
-
head: A pointer to the first node in the list.
-
tail: A pointer to the last node in the list.
-
-
insertAtEnd(int value):
-
This function adds a new node to the end of the list.
-
If the list is empty (
head == nullptr
), the new node becomes both the head and tail. -
Otherwise, the new node is linked to the
tail
, and then thetail
is updated to point to this new node.
-
-
printValues():
- This function prints all the values of the nodes in the list from the head to the tail.
The code uses this approach to efficiently manage the linked list
.
Time Complexity:
-
insertAtEnd: O(1) since we directly update the
tail
pointer, avoiding traversal of the list. -
printValues: O(n) where
n
is the number of nodes, as we need to traverse the entire list to print all elements.
Space Complexity:
- O(n) since we store n nodes in the linked list, with each node storing one value and a pointer to the next node.