Hackerrank Linked List Challenge Help

Hi, I am trying to solve : Insert a Node at the Tail of a Linked List. But I am constantly getting WA. Can anyone point out the mistake in my code. Here is my solution:

 static SinglyLinkedListNode insertNodeAtTail(SinglyLinkedListNode head, int data) {

        var item = new SinglyLinkedListNode(data);
        if(head == null) {
            head = item;
            return head;
        }
        while(head.next != null){
            head = head.next;
        }
        head.next = item;
        return head;

    }

in while loop don’t iterate the head node. Instead store the head node to a temp variable and iterate that temp node. (Reason:- Because at last you have to return the head and if you iterate the head node then in this case you will only get the second last node as your head)

2 Likes

SinglyLinkedListNode* insertNodeAtTail(SinglyLinkedListNode* head, int data) {
if(head == nullptr) return new SinglyLinkedListNode(data);
SinglyLinkedListNode *ptr = head;
while(ptr->next != nullptr){
ptr = ptr->next;
}
ptr->next = new SinglyLinkedListNode(data);
return head;
}

Try This code snippet
in c++14 and c++

Thanks that worked. However, I’v got a question. If I am copying head to a temp variable, that would mean that I am copying the reference of head to a variable. Now, if I am iterating on that temp variable ie I am setting temp = temp.next, I am changing the reference of temp as well as that of head. So how did the value of head not change?

copying the reference means. lets, say you have any variable as x and you want to store the reference of x into some arbitrary variable y then you would code it as.
int &y = x;
now saying cout << x << endl; is equivelent to saying cout << y << endl; as y stores the reference of x and in other words y is just another name of the address that x has.
but in case of head and temp you are not storing the reference instead you are copying the content of head into temp so saying temp = temp->next; is not equal to head = head->next; the above information is true only for c++ and c++14 I have no idea about other languages.