Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LinkedList remove method

What is a doubly linked list's remove method?

like image 453
twodayslate Avatar asked Nov 07 '08 01:11

twodayslate


People also ask

How do you remove a method from a linked list in Java?

A specific element in the LinkedList can be removed using the java. util. LinkedList. remove() method.

What is remove method in Java?

The remove method returns true if an object passed as a parameter is removed from the list. Otherwise, it returns false. The remove method returns the removed element if an index is passed. It throws IndexOutOfBoundsException if the specified index is not in range.

Which method is used to remove an element at the start of a LinkedList object?

LinkedList removeFirst() Method in Java util. LinkedList. removeFirst() method is used to remove the first element from a linked list.


2 Answers

The same algorithm that Bill the Lizard said, but in a graphical way :-)

Remove From Linked List
(source: jaffasoft.co.uk)

like image 143
Christian C. Salvadó Avatar answered Sep 28 '22 16:09

Christian C. Salvadó


The general algorithm is as follows:

  • Find the node to remove.
  • node.previous.next = node.next
  • node.next.previous = node.previous
  • node.previous = null
  • node.next = null
  • Dispose of node if you're in a non-GC environment

You have to check the previous and next nodes for null to see if you're removing the head or the tail, but those are the easy cases.

like image 20
Bill the Lizard Avatar answered Sep 28 '22 16:09

Bill the Lizard