i want to implement a method which takes as an input an integer and a Link and insert the Link in an LinkedList before the Link in position input integer, what i have achieved:
public void insertBefore(int num, String data)
{
Link current = head;
int count = 0;
while (current.next != null)
{
if(count == num) {
Link n = new Link(data);
n.next = current;
current.next = n.previous;
}
}
current = current.next;
count++;
}
However, when i cal the method nothing happens and the Link is not inserted, so any one knows the problem of the method?
As mentioned, your iteration constructs are outside the iteration mechanism. Also, you’re forgetting to set the next element of current’s previous to point to the new link. Not sure what sort of linked list you’re using, but here’s an improvement.
In response to the comments below, a more complete improvement based on your code: