Both solutions are excellent! But if you want to make your codebase cleaner and more maintainable, consider creating a custom LinkedList class. This approach encapsulates the node management, making the code easier to extend and modify.
Here’s how you can do it:
class LinkedList<E> {
private ListNode<E> head;
public void add(E value) {
if (head == null) {
head = new ListNode<>(value, null);
} else {
ListNode<E> current = head;
while (current.next != null) {
current = current.next;
}
current.next = new ListNode<>(value, null);
}
}
public ListNode<E> getHead() {
return head;
}
}
Now, building the list is simplified:
LinkedList<String> list = new LinkedList<>();
list.add("Jeff");
list.add("Brian");
list.add("Negin");
list.add("Alex");
list.add("Alaina");
int n = 3;
ListNode<String> nth = findNtoLast(list.getHead(), n);
System.out.println("The " + n + "th to last value: " + (nth != null ? nth.data : "Not found"));
This approach makes your listnode javamachine solution more modular, preventing direct manipulation of ListNode objects. It also improves reusability and readability, making your codebase cleaner and easier to maintain.