Linked list: removing first element Method 1:

public void removeFirst() {
    if (first == null) throw new NoSuchElementException();
    if (first == last) first = last = null;
    else {
        var second = first.next;
        first.next = null;
        first = second;
    }
}


Method 2:

public void removeFirst() {
    if (first == null) throw new NoSuchElementException();
    if (first == last) first = last = null;
    else               first = first.next;
}


Which method is preferable, speed and memory-wise? Stepping through the debugger, I see no differences in first, next, and last objects or their value attributes - so 'correctness' appears the same, though I ponder about garbage collection.



Base class excerpt:

public class LinkedList {
    private class Node {
        private int value;
        private Node next;

        public Node(int value) {
            this.value = value;
        }
    }
    private Node first;
    private Node last;
}

public void addLast(int value){
    var new_node = new Node(value);

    if (first == null){
        first = last = new_node;
    } else {
        last.next = new_node;
        last = new_node;
    }
}
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.