Let's work through an example to see how to fix your code. Since the values aren't part of the algorithm, I will ignore them in the following discussion. First, assume we already have a list with the following keys:
5 -> 42 -> 69
Now let's analyze the call list.insert(53, x); which should insert a (key, value) pair as the third element in our list.
Start at the beginning of the list.
Link pcurrent = pfirst;
Create a new node.
Link newLink = new Link(key, value);
Make sure we are not at the end of the list.
if(pcurrent != null)
{
Step through the list to find the node where the new link should be inserted.Note that we must be very careful with this loop. It is very easy to have an off-by-one error here.
while(pcurrent.key <= newLink.key && pcurrent.next != null)
{
pcurrent = pcurrent.next;
}
Note that we must be very careful with this loop. It is very easy to have an off-by-one error here. So let's analyze it more carefully.
In our exmple, pcurrent.key starts with a value of 5 which is less than the 53 we are inserting. Also, pcurrent.next is not null. So we move to the next link which has a key of 42. This is still less than 53 and pcurrent.next is still not null. So we move to the next link again. Now pcurrent.next is 69. This isn't less or equal to 53, so the loop terminates.
Link temp = pcurrent.next ;
pcurrent.next = newLink;
newLink.next = temp;
Now we insert after the 69. Ooops! We are off by one. So our loop is incorrect.
To fix this we will need another Link variable, call it previous. Then you can insert after previous and everything should be fine.
Link pcurrent = pfirst;
Link previous = null; // Add this declaration
Link newLink = new Link(key, value);
if(pcurrent != null)
{
while(pcurrent.key <= newLink.key && pcurrent.next != null)
{
previous = pcurrent; // Update previous
pcurrent = pcurrent.next;
}
// insert newLink between previous and next
previous.next = newLink;
newLink.next = current;
}
You should also perform a similar analysis for inserting to an empty list and inserting to the beginning of a list. Note that a debugger can help you with this analysis by showing you exactly what your code is doing. Just be sure that you know what you expect to happen. If you are ever surprised by what your debugger shows, then you know there's a problem.