How to delete a node in a linked list in Java?

2

I have the following code in java but it is not working properly. I need to delete a node from a linked 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;
 }
    
asked by anonymous 10.05.2018 / 19:54

1 answer

2

I think this should work:

public static Node delete(Node head, int position) {
    if (head == null) return null;
    if (position == 0) {
        Node prox = head.next;
        head.next = null;
        return prox;
    }

    int cont = 1;
    Node tmp = head;
    Node tmp2 = head.next;

    while (cont < position) {
        tmp = tmp2;
        tmp2 = tmp2.next;
        cont++;
    }
    tmp.next = tmp2.next;
    tmp2.next = null;
    return head;
 }

There was a compilation error because you declared tmp twice. There were two lines Node tmp=head; .

Another difference is that I make the removed node stop pointing to somewhere in the middle of the list by doing noRetirado.next = null; . This helps the garbage collector and causes if there is a reference to the removed node, that it can not be used to mess with the rest of the list from where it was taken.

I've also changed where some variables are declared to declare them only when they are inevitably needed.

    
10.05.2018 / 20:37