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

Asked

Viewed 214 times

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;
 }

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 severed node stop pointing to some point in the middle of the list while doing noRetirado.next = null;. This helps the garbage collector and causes that if there is a reference to the node removed, it cannot be used to mess with the rest of the list from where it was taken.

I also changed the location where some variables are declared to declare them only when they are unavoidably required.

  • Thanks Victor ! But I had a doubt in the first if, you put head.next= null ... this would not delete position 1?

  • 1

    @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.

  • 1

    @YODA It occurs that head.next = null makes the first node no longer know the second. However, the second is not lost because the reference to it had been stored in prox, which is what is returned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.