Python Day 15: Linked List



Complete the insert function in your editor so that it creates a new Node (pass data as the Node constructor argument) and inserts it at the tail of the linked list referenced by the head parameter. Once the new node is added, return the reference to the head node.

Python Linked List, HackerRank



  1. class Node:
  2. def __init__(self,data):
  3. self.data = data
  4. self.next = None
  5. class Solution:
  6. def display(self,head):
  7. current = head
  8. while current:
  9. print(current.data,end=' ')
  10. current = current.next
  11. def insert(self,head,data):
  12. if (head == None):
  13. head = Node(data)
  14. elif (head.next == None):
  15. head.next = Node(data)
  16. else:
  17. self.insert(head.next, data)
  18. return head
  19. mylist= Solution()
  20. T=int(input())
  21. head=None
  22. for i in range(T):
  23. data=int(input())
  24. head=mylist.insert(head,data)
  25. mylist.display(head);