How to Delete a Node in Link Systems in Java

Linked lists are a basic data structure used to store data. They are perfect for situations in which an unknown quantity of data is going to be stored: the list simply allows the programmer to dynamically allocate memory to the end of the list and create a "chain" of objects that connect to one another. The challenging part comes when one of these nodes must be deleted from somewhere in the middle of the list without the chain's being broken. In such a case you can create two nodes to "point to" items in the list, crawling down the list until finding the node to delete and removing it while maintaining the structure's integrity.

Things You'll Need

  • Text editor
  • Java Developer's Kit
Show More

Instructions

    • 1

      Create a function to remove the node. The function takes a single integer that represents the value of the node. This function assumes the "head" node is the beginning, and each node has a "next" reference along with a single integer value:

      public void removeNode(int value){

      if (head == null){
      return;
      }

      Node tracer = new Node();
      Node tracer2 = new Node();
      tracer = tracer2 = head;

      while (tracer.value != value || tracer != null){
      tracer2 = tracer; //tracer2 always follows tracer
      tracer = tracer.next;
      }

      }

    • 2

      Point the node preceding the node to be deleted to the node following the node to be deleted:

      while (tracer.value != value || tracer == null){
      tracer = tracer.next; //after while loop, tracer will refer to correct node or no node
      }

      if (tracer != null){

      tracer2.next = tracer.next;
      }

    • 3

      Delete the node:

      if (tracer != null){

      tracer2.next = tracer.next;
      }

      tracer = null;

Related Searches:

References

Comments

Related Ads

Featured