Sidharth Samant
Sidharth Samant

Reputation: 786

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.

Upvotes: 0

Views: 72

Answers (3)

Reblochon Masque
Reblochon Masque

Reputation: 36732

I think the error is here:

head = mylist.insert(head, data)

the method Solution.insert() is not returning anything, therefore head is assigned None every time.

When done, Solution.insert() must return the new_node created

Upvotes: 1

letmutx
letmutx

Reputation: 1416

The reason your code doesn't work is because of the None check that you are doing in insert method.

if head == None:
        head = new_node

The head you are updating is local to the function insert and doesn't change head in the loop. So, head is always None in your loop.

Upvotes: 0

Selcuk
Selcuk

Reputation: 59445

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

Upvotes: 2

Related Questions