Sidharth Samant Sidharth Samant - 2 years ago 84
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): = data = None
class Solution:
def display(self,head):
current = head
while current:
current =

def insert(self,head,data):
new_node = Node(data)
if head == None:
head = new_node
current = head
current = = new_node

mylist= Solution()
for i in range(T):

Only the
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
kept on moving forwards instead of staying at the beginning.

Answer Source

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 = current
    return new_node
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download