2
I have the following java code but it’s not working properly. I need to delete a node from a chained list. Someone help me?
/*
Delete Node at a given position in a linked list
head pointer input could be NULL as well for empty list
Node is defined as
class Node {
int data;
Node next;
}
*/
// This is a "method-only" submission.
// You only need to complete this method.
Node Delete(Node head, int position) {
// Complete this method
int cont=1;
Node tmp=head;
if(head==null)
{
return null;
}
if(position==0)
{
Node prox= head.next;
head=prox;
return head;
}
Node tmp=head;
Node tmp2=head.next;
while(cont<position)
{
tmp=tmp2;
tmp2=tmp2.next;
cont++;
}
tmp.next=tmp2.next;
return head;
}
Thanks Victor ! But I had a doubt in the first if, you put head.next= null ... this would not delete position 1?
– Maurício Z.B
@YODA Delete position 0, that is, the first node of the list. In fact, it separates the head from the rest and returns the rest.
– Victor Stafusa
@YODA It occurs that
head.next = nullmakes the first node no longer know the second. However, the second is not lost because the reference to it had been stored inprox, which is what is returned.– Victor Stafusa