Remove element from linked list java

To remove an item in the middle of the linked list, set the previous item's "link" pointer to the "link" pointer of the object you want to remove. For instance, you could add something like this to your LinkedList class:

public void removeNode(Node previousNode, Node nodeToRemove) {
  if (previousNode != null) {
    previousNode.setLink(nodeToRemove.getLink());
  }
}

To think about this better, draw a picture.

 N1 -> N2 -> N3 -> N4

N1's "link" is N2, etc. If you want to remove N2, just set N1's "link" to N3.

 N1 -> N3 -> N4

One approach it to perform a brute force look up.

  • For each element you search if is repeated in the list.
  • If it is, you remove it
  • and go with the next.

As you may see these three steps may be coded quite easy, the point here is to first understand if they do what you want.

This is the pseudo-code for these three points:

forEach( Element a : inList ) do
    // e is the element we want to find repeated.
    forEach( Element b : inList ) do  
         // b is the element in the list.
         if( a == b ) then // repeated
             inList.remove( a ) 
             break;
         endIf
     endFor
 endFor

This approach will allow you to remove all the repeated elements.

Just remember to remove one item, you have to make sure you don't lose the reference it has. So if you have:

n1 -> n2 -> n3

at some point you have to have n1 and n2 pointing to n3 ( that way n1 keeps the reference n2 has )

n1 -> n3  n2 ->n3

and then remove n2 which leaves you:

n1 -> n3

Now how to code that with your specific data structure is a task you have to perform ;)

Tags:

Java