In: Computer Science
Can you fix please?
this is adding the given location of doubly linked list in java
but if I make reverse is not adding the new node that I added but is printing forward correctly.
just fix to me that part
public void addAtLocation(E newNode, int location) {
Node node = new Node(newNode);
node.data = newNode;
Node previous = head;
int counter = 1;
while(counter < location -1)
{
previous =
previous.next;
counter++;
}
Node current = previous.next;
node.next = current;
previous.next = node;
}
I have updated the code, please plug it in your code and test. In case of any query, do comment.
//you have to establish links for node.prev and current.prev to
point to correct node
public void addAtLocation(E newNode, int location)
{
Node node = new Node(newNode);
node.data = newNode;
Node previous = head;
int counter = 1;
while(counter < location -1) {
previous = previous.next;
counter++;
}
//After find a location to insert, you have to update previous
pointers of nodes as well to make reverse working
Node current = previous.next;
node.next = current;
previous.next = node;
//update the previous pointer of node to be inserted with previous
node, to make reverse working
node.prev = previous;
//Just check current node is not null then update the previous of
current node pointing to node (to be inserted)
if (current != null)
{
current.prev = node;
}
}
===================screen shot of the code changed==============================
Please rate the answer. Thanks