carl
carl

Reputation: 623

Why this code for Linked List is showing error in HackerRank?

I have implemented the linked list with this code in IDLE. If I traverse it shows the expected output. But in hackerrank I'm in trouble. What am I missing? Here is the problem link

class Node:
    def __init__(self,data=None,next_node = None):
        self.data = data
        self.next_node = next_node

    def get_data(self):
        return self.data
    def get_next(self):
        return self.next_node
    def set_next(self,new_next):
        self.next_node = new_next
class LL:
    def __init__(self,head=None,tail=None):
       self.head = head   #head
       self.tail = tail   #tail
    def Insert(self,data):
        new_node =  Node(data) #new_node
        new_node.set_next(None)

        if self.head == None:

            self.head = new_node
            self.tail = new_node
        else:
            self.tail.set_next(new_node)
            self.tail = new_node

Upvotes: 1

Views: 616

Answers (2)

Artier
Artier

Reputation: 1673

In your code self.tail.set_next(new_node) is showing error because set_next is function of class Node you can access this function by Node object

TryThis

class Node:

   def __init__(self,data,nextNode=None):
       self.data = data
       self.nextNode = nextNode

   def getData(self):
       return self.data

   def setData(self,val):
       self.data = val

   def getNextNode(self):
       return self.nextNode

   def setNextNode(self,val):
       self.nextNode = val

class LinkedList:

   def __init__(self,head = None):
       self.head = head
       self.size = 0

   def getSize(self):
       return self.size

   def addNode(self,data):
       newNode = Node(data,self.head)
       self.head = newNode
       self.size+=1
       return True

   def printNode(self):
       curr = self.head
       while curr:
           print(curr.data)
           curr = curr.getNextNode()

myList = LinkedList()
print("Inserting")
print(myList.addNode(5))
print(myList.addNode(15))
print(myList.addNode(25))
print("Printing")
myList.printNode()
print("Size")
print(myList.getSize())

Its data structure is looks like enter image description here

Upvotes: 0

cs95
cs95

Reputation: 402413

Getters and setters in python are redundant. Also, you're seriously overcomplicating things.

There are only two cases you need to worry about; The general case, and the corner case when head is None.

Solution 1
Iteration

def Insert(head, data):
    # handle the corner case
    if not head:
        return Node(data)

    # handle the general case
    temp = head
    while temp.next:
        temp = temp.next
    temp.next = Node(data)

    return head

Solution 2
Recursion

def Insert(head, data):
    if not head:
        return Node(data)

    head.next = Insert(head.next, data)
    return head

Both these solutions pass all test cases on Hackerrank.

Upvotes: 1

Related Questions