The next problem is based on Data Structure “Linked List”. It is a data structure having a collection of elements where every element has a reference pointing to the next element in the collection.Each element in linked list is called a node which has commonly two parts; the data part and the reference part which holds the link to the other node.
Complete the insert function in your editor so that it creates a new Node (pass as the Node constructor argument) and inserts it at the tail of the linked list referenced by the parameter. Once the new node is added, return the reference to the node.
4 2 3 4 1
2 3 4 1
HackerRank solution in Python :
class Node: def __init__(self, data): self.data = data self.next = None class Solution: def display(self, head): current = head while current: print(current.data, end=' ') current = current.next def insert(self, head, data): if head is None: head = Node(data) else: curr = head while curr.next: curr = curr.next curr.next = Node(data) return head mylist = Solution() T = int(input()) head = None for i in range(T): data = int(input()) head = mylist.insert(head, data) mylist.display(head)