This is from the book I'm using to study java.
LinkedListNode , integer -> LinkedListNode
This function simply iterates through the linked list k times and returns the node. My question is the following: Is there a point in renaming the parameter from "head" to "current"? Can't I just work on head directly?
LinkedListNode getKthNode(LinkedListNode head, int k) {
LinkedListNode current = head;
while (k > 0 && current != null) {
current = current.next;
k--;
}
return current;
}
In this case, assigning head
to current
is only for the purpose of readability.
The method would behave exactly the same if you modify the head
local variable directly instead of using the current
local variable.
If, on the other hand, the head
reference wasn't passed to the method (i.e. it would be obtained from an instance variable), it would be required to assign it to a local variable in order for your method not to change the head
of the list.
In such case, LinkedListNode getKthNode(int k)
would be a method of a LinkedList
class that has a LinkedListNode head
instance variable.