Skip to main content
added 330 characters in body
Source Link
Joop Eggen
  • 4.7k
  • 15
  • 19

Review points:

  • removeFirst on an empty list should be a no-op, (or throw an exception).
  • last was dangling.
  • Setting things to null of the removed first node, is not done in OOP, is left to the garbage collection. This also removes the need for an extra variable. And the resulting binary code is smaller.

So:

public void removeFirst() { if (first != null) { if (first == last) { // Either this. last = null; } first = first.next; if (first == null) { // Or this. last = null; } } } 

One can only remove the first, when there is one. Then the last might be the biblical first.

This is for the single linked list, where a node has just one next pointer.

public void removeFirst() { if (first != null) { if (first == last) { // Either this. last = null; } first = first.next; if (first == null) { // Or this. last = null; } } } 

One can only remove the first, when there is one. Then the last might be the biblical first.

This is for the single linked list, where a node has just one next pointer.

Review points:

  • removeFirst on an empty list should be a no-op, (or throw an exception).
  • last was dangling.
  • Setting things to null of the removed first node, is not done in OOP, is left to the garbage collection. This also removes the need for an extra variable. And the resulting binary code is smaller.

So:

public void removeFirst() { if (first != null) { if (first == last) { // Either this. last = null; } first = first.next; if (first == null) { // Or this. last = null; } } } 

One can only remove the first, when there is one. Then the last might be the biblical first.

This is for the single linked list, where a node has just one next pointer.

Source Link
Joop Eggen
  • 4.7k
  • 15
  • 19

public void removeFirst() { if (first != null) { if (first == last) { // Either this. last = null; } first = first.next; if (first == null) { // Or this. last = null; } } } 

One can only remove the first, when there is one. Then the last might be the biblical first.

This is for the single linked list, where a node has just one next pointer.