Insert a Node at the Tail of a Linked List. HackerRank Exercise
This exercise is a part of my Linked List topic.
You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty.
You have to complete the SinglyLinkedListNode insertAtTail(SinglyLinkedListNode head, int data) method. It takes two arguments: the head of the linked list and the integer to insert at the tail.
This is a classic Linked List Node realization below
Like in a previous exercise we can easily run a loop through the next variables in each Node. In this exercise, we need to find the last Node and set in his next variable new node.
In a first, if we check if the head variable is a None. If it is true – it means that the head is empty – and we just to return the new Node as a result. It will be head and tail at the same moment.
In a second one, if the head isn’t None than we go through else statement. In the else statement, we need to find the last element of the Linked List. And it is easy because as we understand from 2 first posts about Linked List, that the last’s element next variable should equal to None. And we need to put the new node into the last’s element next variable. When we will find the last node, then we will easily put a new node.
I want to make your attention that we need to return the input head variable, not a tail of the last element in List.
Here I created a Linked List with 3 nodes (1, 2, 3). And the code above will print (1, 2, 3, 34), where 34 is a value of the newly inserted element.
- Linked List Introduction
- Print the Elements of a Linked List.
- Insert a Node at the Head of a Linked list