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; } }