Sidharth Samant Sidharth Samant - 7 months ago 18
Python Question

Trouble with implementing a linked list in Python

There's this HackerRank problem about implementing a linked list. It is pretty basic and I thought I'd do it in a jiffy since I'd done all kinds of linked list implementations in C++. But I'm stuck somewhere.

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,
current = current.next

def insert(self,head,data):
new_node = Node(data)
if head == None:
head = new_node
else:
current = head
while current.next:
current = current.next
current.next = new_node

mylist= Solution()
T=int(input())
head=None
for i in range(T):
data=int(input())
head=mylist.insert(head,data)
mylist.display(head)


Only the
insert
function is editable. The rest of the code is provided by HackerRank and cannot be changed. The code doesn't print anything at the end of the insertions, and when I tried to print out the values while inserting, it seemed like the
head
kept on moving forwards instead of staying at the beginning.

Answer

You are appending the new_node after all the elements, and also you are not returning the newly created node. Modify your insert method like this:

def insert(self,head,data): 
    new_node = Node(data)
    if head is not None:
        current = head
        new_node.next = current
    return new_node