We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Insert a node at a specific position in a linked list
Insert a node at a specific position in a linked list
Sort by
recency
|
1541 Discussions
|
Please Login in order to post a comment
"This operation requires traversing the linked list up to the node just before the desired position. It’s important to handle edge cases, such as inserting at the head (position 0) or beyond the current length of the list. Proper pointer management is critical to ensure no nodes are lost and the list remains intact." Gold365.site
def insertNodeAtPosition(head, data, position): # Write your code here newnode=SinglyLinkedListNode(data) current=head if head is not None: count=1 while current.next: if count==position: newnode.next=current.next current.next=newnode count+=1 current=current.next return head
My Java solution with linear time complexity and constant space complexity:
I noticed that the current test cases might not be testing two important edge cases for this problem:
Inserting at the head of the linked list (position 0):
4 10 20 30 40 99 0 This test case:
Creates a linked list with 4 nodes: 10 -> 20 -> 30 -> 40 Inserts the value 99 at position 0 (the head) Expected output: 99 -> 10 -> 20 -> 30 -> 40
Inserting at the end of the linked list:
3 5 10 15 25 3 This test case:
Creates a linked list with 3 nodes: 5 -> 10 -> 15 Inserts the value 25 at position 3 (the end) Expected output: 5 -> 10 -> 15 -> 25
These edge cases require special handling compared to inserting in the middle. For the first case, we need to return the new node as the head. For the second case, we need to ensure the new node is properly attached at the end of the list. I suggest adding these test cases to ensure that all submissions properly handle insertions at both the beginning and end of the list.
Here is my C++ solution, you can watch the explanation here : https://youtu.be/jCPAp_UIzAs