Dear reader, I hope you are enjoying solving these problems. We will be solving more problems on LinkedList because practice makes a person perfect. Let's try to understand the problem.
Important Links : Problem Link Question Video, Solution Video
Add At Index In Linked List
I don't care if it works on your machine! We are not shipping your machine!
~ Vidiu Platon
Dear reader, I hope you are enjoying solving these problems. We will be solving more problems on LinkedList because practice makes a person perfect. Let's try to understand the problem.
Important Links : Problem Link Question Video, Solution Video
If you faced difficulty understanding the problem I would suggest you watch the question video.
So, let's remind ourselves of the linked list representations.
To understand this better, look at the illustrations. Let's assume we will represent a node this way:
Here we can see the value in the node, the current address of the node, and the next pointer. The next is nothing but stores the address of the next element in the linked list. This way we can traverse and perform other operations in the Linked List.
So, the linked list will look like this:
Let's look into what are the possible values of the index where the new node will be inserted.
Case 1. (idx < 0 or idx > size)
If the index is negative or greater than size then it makes no sense we will simply print invalid arguments and return.
Case 2. (idx is 0)
This is nothing but the addFirst logic, so we can simply reuse that.
Case 3. (idx is size)
This is the case of adding to the last. Thus, we can use the addLast logic.
Case 4. everything else
Now, we can discuss this, here we are guaranteed that there will be a previous node and a next node because the index is neither the first position nor the last position. Let's say we want to add a node of value 200 in the 2nd index. Here I have shown it.
You can see the dotted lines show the expected connections we need to have to include this new node in the linked list.
In other words, we will get the node of the 2-1 -th index, and make it point to the new node, and make the new node point to the previous 2-nd index. Let's look at it step by step.
temp now points to 2-1 = 1st node
And there you go, we have successfully inserted a new element.
Try to write this in code.
java; true";
We are running a single loop to idx-1, at the worst case it might be size-1, so the time complexity will be O(n) linear.
We are not using any auxiliary space other than a single new node, So the space complexity is constant as well.
I hope you have understood the problem and the explanation. If you have some doubts I would insist you watch the solution video. And try to dry run the code, this will make everything clear. See you in the next problem.