I'm studying data structures in Javascript to prep for interviews and am a bit stumped by a return value in the solution. Details below.
The Problem (Reference Link): https://www.hackerrank.com/challenges/delete-a-node-from-a-linked-list/problem
Delete the node at a given position in a linked list and return a reference to the head node. The head is at position 0. The list may be empty after you delete the node. In that case, return a null value.
Boilerplate:
const SinglyLinkedListNode = class {
constructor(nodeData) {
this.data = nodeData;
this.next = null;
}
};
const SinglyLinkedList = class {
constructor() {
this.head = null;
this.tail = null;
}
insertNode(nodeData) {
const node = new SinglyLinkedListNode(nodeData);
if (this.head == null) {
this.head = node;
} else {
this.tail.next = node;
}
this.tail = node;
}
};
function printSinglyLinkedList(node, sep, ws) {
while (node != null) {
ws.write(String(node.data));
node = node.next;
if (node != null) {
ws.write(sep);
}
}
}
And the functional answer:
/*
* Complete the 'deleteNode' function below.
*
* The function is expected to return an INTEGER_SINGLY_LINKED_LIST.
* The function accepts following parameters:
* 1. INTEGER_SINGLY_LINKED_LIST llist
* 2. INTEGER position
*/
/*
* For your reference:
*
* SinglyLinkedListNode {
* int data;
* SinglyLinkedListNode next;
* }
*
*/
function deleteNode(llist, position) {
let head = llist
let currentNode = head
let count = 1
if (head === null) return;
if (position === 0){
head = head.next
return head
if (currentNode === null || currentNode.next === null) return;
while (count < position){
count++
currentNode = currentNode.next
}
currentNode.next = currentNode.next.next
return head
}
This function appears to pass all tests provided.
My question is: Why does returning 'head' give me the correct answer? It does not appear that head is being altered in the function. Returning llist also gives a correct answer as well.
I've tried returning currentNode but obviously that provides the values from currentNode on.
headis altered whenpositionis zero.positionis zero!console.log():)