I am reading algorithm to delete last element of a singly Linked List. Assume I have a Linked List Object called ListNode:
public class ListNode {
private int data;
private ListNode next;
public ListNode(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public void setData(int data) {
this.data = data;
}
public ListNode getNext() {
return this.next;
}
public void setNext(ListNode next) {
this.next = next;
}
}
I found the method to delete the last node of the list is:
public ListNode deleteAtTail(ListNode head) {
if (head == null || head.next == null) return null;
ListNode node = head;
while(node.next.next != null) {
node = node.next;
}
node.next = null;
return head;
}
I am confusing how this code is working since everything is through "node". However, when return head, the last node is deleted. Therefore, I wonder how it is working, is it related to "passed by value" in Java?